Javascript moment.js 或日期验证中的 isSame() 函数

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

isSame() function in moment.js or Date Validation

javascriptvalidationdatemomentjs

提问by user3050590

I need to validate the date from the user and check if it is in a particular format. If yes, then it will be accepted else it will not be. I am looking for sort of

我需要验证来自用户的日期并检查它是否为特定格式。如果是,那么它将被接受,否则它将不被接受。我正在寻找某种

value.match("regular expression") 

The above works fine if, I have to choose from few formats. So, I came across this moment.js and interested in knowing how to use isSame(). I tried implementing it but unsuccessful. Like :

如果我必须从几种格式中进行选择,则上述效果很好。所以,我遇到了这个 moment.js 并有兴趣知道如何使用 isSame()。我尝试实施它但没有成功。喜欢 :

var x=moment("MM/DD/YYYY") ;
x.isSame("28-02-1999");  // am getting false which is right
var x=moment("28-02-1999","DD-MM-YYYY") ;
x.isSame("28-02-1999");  // am getting false which is wrong

So, please help in that. Thanks

所以,请帮忙。谢谢

回答by DanielST

Docs - Is Same

文档 - 相同

Check if a moment is the same as another moment.

moment('2010-10-20').isSame('2010-10-20'); // true

If you want to limit the granularity to a unit other than milliseconds, pass the units as the second parameter.

moment('2010-10-20').isSame('2009-12-31', 'year'); // false
moment('2010-10-20').isSame('2010-01-01', 'year'); // true
moment('2010-10-20').isSame('2010-12-31', 'year'); // true
moment('2010-10-20').isSame('2011-01-01', 'year'); // false

检查一个时刻是否与另一个时刻相同。

moment('2010-10-20').isSame('2010-10-20'); // true

如果要将粒度限制为毫秒以外的单位,请将单位作为第二个参数传递。

moment('2010-10-20').isSame('2009-12-31', 'year'); // false
moment('2010-10-20').isSame('2010-01-01', 'year'); // true
moment('2010-10-20').isSame('2010-12-31', 'year'); // true
moment('2010-10-20').isSame('2011-01-01', 'year'); // false

Your code

你的代码

var x=moment("28-02-1999","DD-MM-YYYY"); // working
x.isSame("28-02-1999"); // comparing x to an unrecognizable string

If you try moment("28-02-1999"), you get an invalid date. So comparing x to an invalid date string returns false.

如果你尝试moment("28-02-1999"),你会得到一个无效的日期。因此,将 x 与无效的日期字符串进行比较会返回 false。

To fix it, either use the default date format(ISO 8601):

要修复它,请使用默认日期格式(ISO 8601):

var x = moment("28-02-1999","DD-MM-YYYY");
x.isSame("1999-02-28"); // YYYY-MM-DD

Or pass isSamea moment object.

或者传递isSame一个时刻对象。

var x = moment("28-02-1999","DD-MM-YYYY");
x.isSame( moment("28-02-1999","DD-MM-YYYY") );