isSame()函数在moment.js或Date验证 [英] isSame() function in moment.js or Date Validation

查看:3558
本文介绍了isSame()函数在moment.js或Date验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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") 

上述工作正常,如果我必须从几种格式中选择。所以,我遇到这个时刻js,有兴趣知道如何使用isSame()。我尝试实现,但不成功。喜欢:

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 :

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

推荐答案

文件 - 相同



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

您的代码

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

如果尝试 -02-1999),您的日期无效。因此,将x与无效的日期字符串进行比较返回false。

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

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

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

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

或通过 isSame 一个对象。

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

这篇关于isSame()函数在moment.js或Date验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆