如何正确创建功能的日期对象

时间:2018-07-25 23:49:58

标签: javascript reactjs date datepicker

我在表单上的字段中有一个日期选择器,允许用户选择日期。提交表单后,date对象将解析为后端API要求的正确格式的字符串。当我尝试获取用于填充表单的对象时,该输入字段的返回类型以字符串形式返回。如果我尝试传入字符串,则页面将崩溃。

当API返回应该填充如下所示的输入字段的字符串变量时,就会发生确切的问题。该程序当前引发一个错误,指出date.clone不是一个函数。

有人可以帮我弄清楚如何从后端传递字符串日期,以便正确显示在前端吗?

此函数接收date对象并为后端创建字符串。后端以字符串形式返回lastDateAccessed,而lastDateAccessedHolder是在输入字段中可见的内容。

handleDateChange(date) {
    this.setState({ lastDateAccessedHolder: date });

    var lastDate = new Date(date);
    var day = lastDate.getDate();
    if(day.toString().length === 1)
    {
        day = '0' + day;
    }

    var month = lastDate.getMonth() + 1;
    if(month.toString().length === 1)
    {
        month = '0' + month;
    }

    var year = lastDate.getFullYear();
    this.setState(
        {lastDateAccessed: year+"-"+month+"-"+day},
        () => console.log(this.state.lastDateAccessed)
    );
}

这是使用日期选择器的行,并显示输入字段:

<DatePicker selected={this.state.lastDateAccessedHolder} onChange={this.handleDateChange}/>

更新:后端将返回responseData.lastDateAccessed。此变量的日期将为“ 2018-09-09”或“ 2016-12-03”。

更新2:我在API的GET函数中运行的代码是:

var dateString = responseData.lastDateAccessed;
     var finalDate = dateString.split('-');
     var done = new Date(finalDate[0], finalDate[1] - 1, finalDate[2]);
     this.setState({lastDateAccessedHolder: done});

错误:

index.js:318 Uncaught TypeError: date.clone is not a function
at safeDateFormat (index.js:318)
at DatePicker._this.renderDateInput (index.js:2844)
at DatePicker.render (index.js:2916)
at finishClassComponent (react-dom.development.js:8389)
at updateClassComponent (react-dom.development.js:8357)
at beginWork (react-dom.development.js:8982)
at performUnitOfWork (react-dom.development.js:11814)
at workLoop (react-dom.development.js:11843)
at HTMLUnknownElement.callCallback (react-dom.development.js:100)
at Object.invokeGuardedCallbackDev (react-dom.development.js:138)
at invokeGuardedCallback (react-dom.development.js:187)
at replayUnitOfWork (react-dom.development.js:11318)
at renderRoot (react-dom.development.js:11885)
at performWorkOnRoot (react-dom.development.js:12449)
at performWork (react-dom.development.js:12370)
at performSyncWork (react-dom.development.js:12347)
at requestWork (react-dom.development.js:12247)
at scheduleWorkImpl (react-dom.development.js:12122)
at scheduleWork (react-dom.development.js:12082)
at Object.enqueueSetState (react-dom.development.js:6644)
at addAsset../node_modules/react/cjs/react.development.js.Component.setState (react.development.js:238)
at addAsset.js:71

1 个答案:

答案 0 :(得分:1)

此答案假设您只需要日期。

确保GET请求返回的字符串遵循ISO格式:YYYY-MM-DD

有关更多详细信息,您可以参考以下答案-link 1link 2

更新:在进一步挖掘时,我遇到了this issue,它建议按照其中一项评论中的建议使用日期打包日期

<DatePicker
  className={styles.datePicker}
  selected={moment(this.props.endDate)}
  onChange={this.handleChangeEnd}
/>