Javascript 时刻格式返回无效日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/43848300/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:12:13  来源:igfitidea点击:

Moment format returns invalid date

javascriptdatemomentjs

提问by user7334203

i have a date which i formated using moment to be shown like this: 03/04/2105. I want to transform it to iso using moment again. As a result i'm writing:

我有一个使用时刻格式化的日期,如下所示:03/04/2105。我想再次使用 moment 将其转换为 iso。结果我在写:

const IsoDateTo = moment(dateTo).format('YYYY-MM-DD[T]HH:mm:ss');

The date to is 23/04/2105 but the IsoDateTo is returning something like this: 2105-03-04T00:00:00 Also when i enter a date greater than 12 it returns me Invalid Date. Why is this happening?

日期为 23/04/2105,但 IsoDateTo 返回如下内容:2105-03-04T00:00:00 此外,当我输入大于 12 的日期时,它返回无效日期。为什么会这样?

回答by Vladimir M

To make sure that you are correctly parsing the string you want to pass the expected string format along to the momentjs (something like this):

为了确保您正确解析了您想要将预期的字符串格式传递给 momentjs 的字符串(类似这样):

const IsoDateTo = moment(dateTo,'DD/MM/YYYY').format('YYYY-MM-DD[T]HH:mm:ss');

回答by str

You cannot just throw any date format into it and expect it to magically recognize the format. Moment.js relies on the date parsing functionality of JavaScript if you do not specify and other format. According to the MDN specification of Date, "dateString" can be either IETF-compliant RFC 2822 timestamps or a version of ISO8601. Your date string is neither of it.

您不能只是将任何日期格式放入其中并期望它神奇地识别该格式。如果您不指定和其他格式,则 Moment.js 依赖于 JavaScript 的日期解析功能。根据DateMDN 规范,“dateString”可以是符合 IETF 的 RFC 2822 时间戳或 ISO8601 的版本。您的日期字符串都不是。

It is usually the best to use a date format like YYYY-MM-DD.

通常最好使用像YYYY-MM-DD.

const IsoDateTo = moment('2105-03-04').format('YYYY-MM-DD[T]HH:mm:ss');