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".
I need to check if this date is a valid date.
I have tried following things
var d = moment("2016-10-19",dateFormat);
d.isValid()
is returning false
every time. Does not Moment.js parse the date in the given format?
Then I tried to format the date in DD-MM-YYYY
first and then pass it to Moment.js:
var d = moment("2016-10-19").format(dateFormat);
var date = moment(d, dateFormat);
Now date.isValid()
is giving me the desired result, but here the Moment.js date object is created twice. How can I avoid this? Is there a better solution?
FYI I am not allowed to change the dateFormat
.
Was able to find the solution.
Since the date I am getting is in ISO format, only providing date to moment will validate it, no need to pass the dateFormat.
var date = moment("2016-10-19");
And then date.isValid()
gives desired result.
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.
Here you go: Working Fidddle
$(function(){
var dateFormat = 'DD-MM-YYYY';
alert(moment(moment("2012-10-19").format(dateFormat),dateFormat,true).isValid());
});
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
Try this one. It is not nice but it will work as long as the input is constant format from your date picker.
It is badDate coming from your picker in this example
https://jsfiddle.net/xs8tvox9/
var dateFormat = 'DD-MM-YYYY'
var badDate = "2016-10-19";
var splittedDate = badDate.split('-');
if (splittedDate.length == 3) {
var d = moment(splittedDate[2]+"-"+splittedDate[1]+"-"+splittedDate[0], dateFormat);
alert(d.isValid())
} else {
//incorrectFormat
}