javascript 使用 moment.js 验证 ISO 8601 日期

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22164541/
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-10-27 22:34:39  来源:igfitidea点击:

Validating a ISO 8601 date using moment.js

javascriptmomentjs

提问by user1184100

I'm trying to validate a ISO 8601 date in javascript using moment.js

我正在尝试使用 moment.js 在 javascript 中验证 ISO 8601 日期

console.log(moment("2011-10-10T14:48:00", "YYYY-MM-DD", true).isValid())

It returns false. Where am I going wrong ? Is the date type format incorrect ?

它返回假。我哪里错了?日期类型格式不正确吗?

version:Moment 2.5.1

版本:时刻 2.5.1

采纳答案by antimatter

Not sure why Praveen's example works in jsfiddle, but the reason your sample doesn't work is because the format isn't YYYY-MM-DD. It includes the time as well, so it's considered invalid. If you try it without the time in the date, it returns true.

不确定为什么 Praveen 的示例在 jsfiddle 中有效,但您的示例不起作用的原因是因为格式不是 YYYY-MM-DD。它也包括时间,所以它被认为是无效的。如果您在没有日期时间的情况下尝试,则返回 true。

Try this instead:
moment("2011-10-10T14:48:00", "YYYY-MM-DDTHH:mm:ss", true).isValid()

试试这个:
moment("2011-10-10T14:48:00", "YYYY-MM-DDTHH:mm:ss", true).isValid()

回答by wawka

To avoid using string pattern as a second argument, you can just call:

为了避免使用字符串模式作为第二个参数,你可以调用:

moment("2011-10-10T14:48:00", moment.ISO_8601).isValid() // true
moment("2016-10-13T08:35:47.510Z", moment.ISO_8601).isValid() // true

回答by Praveen

Okay, I found it.

好的,我找到了。

As per the documentation,

根据文档

As of version 2.3.0, you may specify a booleanfor the last argument to make Moment use strict parsing. Strict parsing requires that the format and input match exactly

从 2.3.0 版本开始,您可以boolean为最后一个参数指定 a以使 Moment 使用严格解析。严格解析要求格式和输入完全匹配

because you use strict operation, it returns false. To overcome that use below code:

因为您使用了严格的操作,所以它返回false. 为了克服使用下面的代码:

alert(moment("2011-10-10T14:48:00", "YYYY-MM-DDTHH:mm:ss", true).isValid())
//This will return true

demo1

演示1

If you removethe strict parsing,

如果你删除strict parsing

alert(moment("2011-10-10T14:48:00", "YYYY-MM-DD").isValid())
//This will return true

demo2

演示2

回答by Cris

use this to match part of your date

用它来匹配你的日期的一部分

console.log(moment("2011-10-10T14:48:00", "YYYY-MM-DD", false).isValid())

if you want exact format match then

如果你想要精确的格式匹配那么

console.log(moment("2011-10-10T14:48:00", "YYYY-MM-DDTHH:mm:ss", true).isValid())