Following is the scenario:
I have a String
date and a date format which is different. Ex.:
date: 2016-10-19
dateFormat: \"DD-MM-YYYY\".
var date = moment('2016-10-19', 'DD-MM-YYYY', true);
You should add a third argument when invoking moment
that enforces strict parsing. Here is the relevant portion of the moment documentation http://momentjs.com/docs/#/parsing/string-format/ It is near the end of the section.
If the date is valid then the getTime()
will always be equal to itself.
var date = new Date('2019-12-12');
if(date.getTime() - date.getTime() === 0) {
console.log('Date is valid');
} else {
console.log('Date is invalid');
}
Here you go: Working Fiffffdle
$(function(){
var dateFormat = 'DD-MM-YYYY';
alert(moment(moment("2012-10-19").format(dateFormat),dateFormat,true).isValid());
});
console.log(` moment('2019-09-01', 'YYYY-MM-DD').isValid()? ` +moment('2019-09-01', 'YYYY-MM-DD').isValid())
console.log(` moment('2019-22-01', 'YYYY-DD-MM').isValid()? ` +moment('2019-22-01', 'YYYY-DD-MM').isValid())
console.log(` moment('2019-22-22', 'YYYY-DD-MM').isValid()? ` +moment('2019-22-22', 'YYYY-DD-MM').isValid())
console.log(` moment('undefined', 'YYYY-DD-MM').isValid()? ` +moment('undefined', 'YYYY-DD-MM').isValid())
moment('2019-09-01', 'YYYY-MM-DD').isValid()? true
moment('2019-22-01', 'YYYY-DD-MM').isValid()? true
moment('2019-22-22', 'YYYY-DD-MM').isValid()? false
moment('undefined', 'YYYY-DD-MM').isValid()? false
I use moment along with new Date to handle cases of undefined
data values:
const date = moment(new Date("2016-10-19"));
because of: moment(undefined).isValid() == true
where as the better way: moment(new Date(undefined)).isValid() == false
Sorry, but did any of the given solutions on this thread actually answer the question that was asked?
I have a String date and a date format which is different. Ex.: date: 2016-10-19 dateFormat: "DD-MM-YYYY". I need to check if this date is a valid date.
The following works for me...
const date = '2016-10-19';
const dateFormat = 'DD-MM-YYYY';
const toDateFormat = moment(new Date(date)).format(dateFormat);
moment(toDateFormat, dateFormat, true).isValid();
// Note: `new Date()` circumvents the warning that
// Moment throws (https://momentjs.com/guides/#/warnings/js-date/),
// but may not be optimal.
But honestly, don't understand why moment.isDate()
(as documented) only accepts an object. Should also support a string in my opinion.