check format of date with moment.js

折月煮酒 提交于 2019-12-05 15:10:30

问题


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


回答1:


For checking date format you could use:

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



回答2:


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

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



回答3:


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



回答4:


In Typescript:

The import statement currently used (import * as moment from "moment") is a module import, and modules are not allowed to be called (i.e. moment() is forbidden). All named exports of moment can be accesed through the importet object. The default export can be called via moment.default() In my opinion the correct solution is to change.

import * as moment from "moment" to import moment from "moment"

So we just import the default export and name it moment.



来源:https://stackoverflow.com/questions/28587018/check-format-of-date-with-moment-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!