ISO 8601 date check using .js moment

I am trying to check the ISO 8601 date in javascript using moment.js

console.log(moment("2011-10-10T14:48:00", "YYYY-MM-DD", true).isValid()) 

It returns false. Where am I going wrong? Does the date format of the date match?

version: Moment 2.5.1

+7
javascript momentjs
source share
4 answers

Not sure why the Praveen example works in jsfiddle, but the reason your sample doesn't work is because the format is not YYYY-MM-DD. It also includes time, so it is considered invalid. If you try it without time in the date, it will return true.

Try this instead:
moment("2011-10-10T14:48:00", "YYYY-MM-DDTHH:mm:ss", true).isValid()

+8
source share

To avoid using a string pattern as the second argument, you can simply call:

 moment("2011-10-10T14:48:00", moment.ISO_8601).isValid() // true moment("2016-10-13T08:35:47.510Z", moment.ISO_8601).isValid() // true 
+23
source share

Ok, I found it.

According to the documentation ,

Starting with version 2.3.0, you can specify boolean for the last argument to force Moment to use strict parsing. Strict analysis requires that the format and input match exactly

because you are using a strict operation, it returns false . To overcome this use below code:

 alert(moment("2011-10-10T14:48:00", "YYYY-MM-DDTHH:mm:ss", true).isValid()) //This will return true 

demo1

If you remove strict parsing ,

 alert(moment("2011-10-10T14:48:00", "YYYY-MM-DD").isValid()) //This will return true 

demo2

+3
source share

use this to match part of your date

 console.log(moment("2011-10-10T14:48:00", "YYYY-MM-DD", false).isValid()) 

if you need the exact format then

 console.log(moment("2011-10-10T14:48:00", "YYYY-MM-DDTHH:mm:ss", true).isValid()) 
+1
source share

All Articles