22

I'm trying out date-fns v2.

I got some errors when I ran:

parseISO("Apr 9, 2020, 12:00:00 am");

or

parseISO("Apr 9, 2020, 12:00:00 am", "MMM M, YYYY, hh:mm:ss aaaa");

but this worked fine:

new Date("Apr 9, 2020, 12:00:00 am");

I'm trying to understand when I should use one or the other but I couldn't find the docs for parseISO().

Dev01
  • 13,292
  • 19
  • 70
  • 124

3 Answers3

20

Docs for parseISO here. Basically parseISO tries to parse string which holds ISO formatted date string like '2019-09-25T14:34:32.999Z'.

What you are trying to parse is internationalized string. I.e. 'Apr 9, 2020, 12:00:00 am' is US locale formatted date string.

new Date() works because it relays on locale of your environment (browser or node), the string you are passing to it is matching format of your locale. If you will pass french locale formatted date string, will most likely fail.

To parse internationalized string, you may also look at parse which will also take the format of passed date string.

If you pass your dates over the wire (like HTTP rest API or database) you should be already decided on format to pass/store your date times. Normally it is either ISO formatted date string, number of milliseconds in UTC since 1970 or any other suitable for your case. Then as per specification of your "wire" or "store", you will do parseISO or new Date(milliseconds).

If you do some browser based web app, you should be considering the local of your user. Then parsing may become cumbersome, as you have take care of locale and/or timezone of your user.

muradm
  • 1,973
  • 19
  • 30
2

Apr 9, 2020, 12:00:00 am doesn't match the ISO 8601 format that is expected from parseDate. This is an example for a correct ISO 8601 date string: 2020-11-20T10:36:01.516Z.

Note that MDN strongly discourages the use of new Date(dateString) or Date.parse(dateString):

Note: Parsing of date strings with the Date constructor (and Date.parse(), which works the same way) is strongly discouraged due to browser differences and inconsistencies.

(source)

amann
  • 5,449
  • 4
  • 38
  • 46
  • 1
    The current [docs](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/Date#several_ways_to_create_a_date_object) say that `new Date()` works reliably for ISO-8601-compliant strings (quote: `const birthday = new Date("1995-12-17T03:24:00"); // This is ISO-8601-compliant and will work reliably`). [parseISO](https://date-fns.org/docs/parseISO) only accepts ISO-8601-compliant strings, but I would assume they use `new Date` or `Date.format` under the hood. – ArneHugo Dec 06 '22 at 14:39
2

casual observation: shouldn't the 4th capitol M be a lowercasee d ? From MMM M, YYYY, hh:mm:ss aaaa to MMM d, YYYY, hh:mm:ss aaaa

Radagast the Brown
  • 3,156
  • 3
  • 27
  • 40
D Waters
  • 21
  • 1