2

I have an issue with date parsing in javascript.

I could have dates in different formats so I need to have universal parser. I use Date.parse(), but can someone explain me why that's happen:

Date.parse("1/07/2018");
1515279600000

but

Date.parse("26/07/2018");
NaN

Today is 26th Jul, so why it has Nan??

zleek
  • 201
  • 4
  • 16

4 Answers4

5

Neither of those formats is necessarily supported by the Date object. The only format it's required to support is the ISO-8601 variant described by the specification.

Use the multi-argument constructor (note: 6 = July, the months start at 0):

// To get a Date instance
new Date(2018, 6, 26);           // Local time
new Date(Date.UTC(2018, 6, 26)); // UTC

// To get the milliseconds-since-the-Epoch value
new Date(2018, 6, 26).getTime(); // Local
Date.UTC(2018, 6, 26);           // UTC

Most (all?) JavaScript engines will also accept a U.S.-style date (even in non-U.S. locales) in the form mm/dd/yyyy, but you can't be sure whether it will parse that in local time or UTC. That's why your first example works (sort of, the result is January 7th, not July 1st), and your second doesn't (the "month" isn't valid).

If you don't want to handle the parsing yourself, there are libraries like Moment that do it (and a lot of other things) for you.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

JavaScript expects your dates to be in a specific format when separated by a slash. This doesn't mean you can't use the dates that are formatted the other way, you just need to know when they are. If you have a date formatted dd-MM-yyyy you can change it to the proper format like this:

let date = "26/07/2018"
date = date.split('/');

date = new Date(`${date[1]}/${date[0]}/${date[2]}`)
codeWonderland
  • 297
  • 1
  • 11
0

According to Mozilla documentation. ISO 8601 format (and other variants) like "2017-04-16" are expected. Your format isn't supported.

I would recommend sticking to the standard formats, as even if non-standard formats might be supported, it might not work on all browsers

-2

Please have a look at Data.parse method doc: https://developer.mozilla.org/pl/docs/Web/JavaScript/Referencje/Obiekty/Date/parse

You need to pass it like mm/dd/yyyy or you can do it like this:

Date.parse("07/26/2018");
Date.parse("Jul 26, 2018");
Zeeshan Tariq
  • 604
  • 5
  • 10