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.