gpt4 book ai didi

javascript - 如何正确为函数创建日期对象

转载 作者:行者123 更新时间:2023-12-03 01:26:18 24 4
gpt4 key购买 nike

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

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

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

该函数接收日期对象并为后端创建字符串。后端以字符串形式返回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

最佳答案

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

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

更多详情,您可以引用这些答案 - link 1link 2

更新:在更多的挖掘中,我发现了 this issue这建议按照评论之一的建议使用 moment 来打包日期

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

关于javascript - 如何正确为函数创建日期对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51529176/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com