check format of date with moment.js

2020-07-03 06:37发布

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

 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 ..

4条回答
We Are One
2楼-- · 2020-07-03 07:02

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

moment(scope.modelValue, 'DD-MMM-YYYY HH:mm a', true).isValid()
查看更多
ら.Afraid
3楼-- · 2020-07-03 07:13

For checking date format you could use:

moment(checked_date, DATE_FORMAT).format(DATE_FORMAT) === checked_date
查看更多
霸刀☆藐视天下
4楼-- · 2020-07-03 07:18

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});

查看更多
放荡不羁爱自由
5楼-- · 2020-07-03 07:21

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
查看更多
登录 后发表回答