Tuesday, June 4, 2024
 Popular · Latest · Hot · Upcoming
127
rated 0 times [  130] [ 3]  / answers: 1 / hits: 17510  / 7 Years ago, fri, october 6, 2017, 12:00:00

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


More From » validation

 Answers
48

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>




[#56303] Monday, October 2, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
wyattkennyc

Total Points: 650
Total Questions: 102
Total Answers: 90

Location: Monaco
Member since Mon, May 23, 2022
2 Years ago
;