Javascript 使用 moment.js 检查日期格式

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

check format of date with moment.js

javascriptdatedate-formatmomentjs

提问by rishi

I am taking input from calendar in my screen which is of this type

我正在从我的屏幕中的日历中获取输入,这是这种类型

DD-MMM-YYYY HH:mm a

but user can provide date from keyboard. Now I have to check whether user has provided the date in correct format or not. I am heavily using moment.js in my application and validating it like this

但用户可以从键盘提供日期。现在我必须检查用户是否以正确的格式提供了日期。我在我的应用程序中大量使用 moment.js 并像这样验证它

 if(angular.equals(moment(scope.modelValue).format('DD-MMM-YYYY HH:mm a'), 'Invalid date'))
{
       alert('date is not correct');

}
else
{
alert('date is correct');
}

It is working fine but the problem is if I provide input like '18-Feb-2015 2' then it is converted to '18-Feb-2015 00:00 am'. so now how to check that format is exactly what I want ? please help ..

它工作正常,但问题是如果我提供像“18-Feb-2015 2”这样的输入,那么它会被转换为“18-Feb-2015 00:00 am”。那么现在如何检查该格式正是我想要的?请帮忙 ..

回答by wallop

if it's just for checking the below is a better alternative

如果只是为了检查以下是更好的选择

moment(scope.modelValue, 'DD-MMM-YYYY HH:mm a', true).isValid()

回答by EAndreyF

For checking date format you could use:

要检查日期格式,您可以使用:

moment(checked_date, DATE_FORMAT).format(DATE_FORMAT) === checked_date

回答by Asif Karim Bherani

If you don't have a particular date format then you can also use Array of formats,

如果您没有特定的日期格式,那么您也可以使用格式数组,

moment(checked_date, [DATE_FORMAT1, DATE_FORMAT2]).format(DATE_FORMAT)
 === checked_date

回答by Lucas

This is much better:

这要好得多:

if (!moment(checked_date, DATE_FORMAT).isValid()) throw Error(Argument passed is invalid: checked_date. Date format must be ${DATE_FORMAT});

if (!moment(checked_date, DATE_FORMAT).isValid()) throw Error( Argument passed is invalid: checked_date. Date format must be ${DATE_FORMAT});