最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Dated-fns can't parse ISO Date - Stack Overflow

programmeradmin2浏览0评论

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.

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.

Share Improve this question asked Sep 1, 2019 at 12:27 Dave3of5Dave3of5 7307 silver badges24 bronze badges 3
  • 4 You can pass that ISO string directly to new Date(isoString) – charlietfl Commented Sep 1, 2019 at 12:35
  • Can you show full code? Because it does work on their official documentation in console. – Leo Odishvili Commented Sep 1, 2019 at 12:35
  • I'll create a repro sorry I should have in the original – Dave3of5 Commented Sep 1, 2019 at 13:39
Add a ment  | 

2 Answers 2

Reset to default 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

Correct answer:

import { format } from 'date-fns';

format(new Date(v), 'yyyy-MM-dd'); // or another desired format
发布评论

评论列表(0)

  1. 暂无评论