Reputation: 1406
I am unable to find an existing question/answer on how to validate a date input using moment.js to ensure that it is in this format, "2017-12-31T23:59:59Z".
Given that I've got a date as a string, "2017-12-31T23:59:59Z", how can validate that the date string is strictly in the format specified, "YYYY-MM-DDThh:mm:ssZ".
I've tried the following and it does not seem to work for me.
var dateTime = "2017-12-31T23:59:59Z";
var utc = moment(dateTime, "YYYY-MM-DDThh:mm:ssZ", true)
var isUTC = utc.isValid(dateTime);
console.log(isUTC);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Could anyone please provide a couple of examples?
Thanks in advance -R
Upvotes: 3
Views: 19903
Reputation: 31482
Moment tokens are case sensitive, you should use uppercase HH
to parse 0-23
hours, hh
is for parsing 1-12
. See moment(String, String, Boolean)
docs.
Here a live example:
var dateTime = "2017-12-31T23:59:59Z";
var utc = moment(dateTime, "YYYY-MM-DDThh:mm:ssZ", true)
var isUTC = utc.isValid();
console.log(isUTC);
utc = moment(dateTime, "YYYY-MM-DDTHH:mm:ssZ", true)
isUTC = utc.isValid();
console.log(isUTC);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Upvotes: 12