Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate date with Moment.js to a specified format?

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

like image 721
Roobie Avatar asked Nov 19 '25 07:11

Roobie


1 Answers

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>
like image 122
VincenzoC Avatar answered Nov 20 '25 22:11

VincenzoC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!