如何在Material UI React中的DatePicker中格式化get和format Date

时间:2018-02-27 14:54:05

标签: javascript reactjs material-ui

我有一个日期选择器,并希望只获得YYYY-MM-DD格式的日期。 默认的日期时间格式为:

Tue Feb 06 2018 00:00:00 GMT+0200 (FLE Standard Time)

如何设置此日期选择器的格式? 另外,如何将字段的颜色更改为另一种颜色,即写入日期的字段。

handleChangeDate = (event, date) => {
this.setState({
  controllerDate: date
});
 };

onSubmitHandler(e){
    e.preventDefault();
    console.log(this.state.value)
    console.log(this.state.controllerDate)
  }

 <div className="col-md-3">           
              <DatePicker hintText="Изберете дата" onChange={ this.handleChangeDate } />
 </div>

1 个答案:

答案 0 :(得分:2)

以下是以 YYYY-MM-DD 格式获取日期的解决方案

&#13;
&#13;
class DatePickerExampleSimple extends React.Component {
    constructor(props) {
        super(props);
        this.state = {}
        this.handleChangeDate = this.handleChangeDate.bind(this);
        this.formatDate = this.formatDate.bind(this);
    }

    formatDate(date) {
        let d = new Date(date),
            month = '' + (d.getMonth() + 1),
            day = '' + d.getDate(),
            year = d.getFullYear();

        if (month.length < 2) month = '0' + month;
        if (day.length < 2) day = '0' + day;

        return [year, month, day].join('-');
    }

    handleChangeDate = (event, date) => {
        let formattedDate = this.formatDate(date);
        console.log(formattedDate);
        this.setState({
            controllerDate: formattedDate
        });
    };

  render(){
      return(<div>
          <DatePicker hintText="Изберете дата" onChange={ this.handleChangeDate } />
          <div>New selected value is {this.state.controllerDate}</div>
      </div>)
  }
};
export default DatePickerExampleSimple;
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
&#13;
&#13;
&#13;