Dated-fns can't parse ISO Date
Asked Answered
D

2

5

Using 2.0.0-beta.4 of date-fns I'm stuggling to figure out the format string for parsing and ISO date. My date string is as follows:

2019-08-31T14:36:28.511Z

And the parsing code is as follows:

parse(v, 'yyyy-MM-dd', new Date());

v here is the string and this doesn't parse. I've also tried the following:

parse(v, 'yyyy-MM-dd[T]hh:mm:ss.SSSZ', new Date());

This also doesn't parse as I get 'Invalid Date' returned for all of these. This problem is actually in a third party library that I'm using so I can't change it from using the parse rather than parseISO function.

Dedal answered 1/9, 2019 at 12:27 Comment(3)
You can pass that ISO string directly to new Date(isoString)Yockey
Can you show full code? Because it does work on their official documentation in console.Kress
I'll create a repro sorry I should have in the originalDedal
C
5

parse expects date string (first argument) to match the format (second argument) in an exact manner.

In your case, it should be this,

parse("2019-08-31T14:36:28.511Z", "yyyy-MM-dd'T'HH:mm:ss.SSSX", new Date())

Please refer parse documentation to form the correct format string.

Here is the working example, https://codesandbox.io/s/date-fns-playground-forked-t7mvqe?file=/src/index.js

Chiropody answered 1/8, 2022 at 2:53 Comment(0)
S
1

Correct answer:

import { format } from 'date-fns';

format(new Date(v), 'yyyy-MM-dd'); // or another desired format
Scrooge answered 9/12, 2020 at 3:15 Comment(3)
That's not a good idea for iOS (MacOS) + Safari.Torietorii
What's the difference between DD and dd. Also why does mm give wrong value. There is confusion around uppercase and lowercaseEldredge
@SteveTomlin The difference (based on the docs) is that dd represents the day of month, e.g., 01, 02, ..., 31 whereas DD represents the day of year, e.g., 01, 02, ..., 366. Pay attention to the left-padded zeros because using d and D will not have any zero-padding.Desilva

© 2022 - 2025 — McMap. All rights reserved.