简体   繁体   中英

Why moment(date).isValid() returns wrong result

when I check the following date it returns true result, Why?

const value = "3";
if (moment(new Date(value), "DD-MM-YYYY HH:mm", true).isValid())  // true
{ }

or

const value = "3";
if (moment(new Date(value)).isValid())  // true
{ }

That is because new Date("3") is valid date and

 console.log(new Date("3"))

This is one of those cases that shows you need to sanitize your date strings and should not depend on the native parser, unless you are sure your strings have already been validated and are conformant.

ECMA-262 Date(value) constructor specs
Date.parse

If the String does not conform to that format the function may fall back to any implementation-specific heuristics or implementation-specific date formats.

So it's not conformant to "Date Time String Format" , which requires the string to start with "YYYY", so it goes to an implementation specific parsing that is similar to the rules for above, but using the form: "MM-DD-YYYY".

The purpose of using strict mode (setting third argument of moment() to true) is to let moment do the string parsing and determine if it fits the formats that you provide (to for example avoid unexpected parsing behavior like this). If you use Date() to parse, you are no longer using moment's strict mode to validate the string fits your required format.

 let value = "3"; function checkDate(value){ console.log(value, moment(value, "DD-MM-YYYY HH:mm", true).isValid()? 'valid': 'invalid') } value = "01-01-2011 11:22" checkDate(value) value = "01-01-2011 11:22Z" checkDate(value) value = "3" checkDate(value) value = new Date("3").toString() checkDate(value) value = new Date('INVALID DATE') checkDate(value)
 <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.25.3/moment-with-locales.min.js" integrity="sha256-8d6kI5cQEwofkZmaPTRbKgyD70GN5mDpTYNP9YWhTlI=" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.28/moment-timezone-with-data.js" integrity="sha256-O1PdKrSbpAYWSBteb7yX/CMmHhu3US31mtCbsryGwaY=" crossorigin="anonymous"></script>

If you don't need to validate the date string (for example to prevent unexpected parsing behavior), don't need to worry about non-modern browsers, and really just need to parse conforming Date strings and format to basic string formats, you could just use native Date() with Intl.DateTimeFormat or Date.prototype.toLocaleString .
TL;DR the way you are using it right now implies that you don't actually need moment

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM