dayjs() telling me invalid date for this date string
Asked Answered
W

2

12

DayJs

Using it on the browser if that matters (firefox + Vue + typescript).

This is my date string

2021-02-05 12:00 AM

It fusses about the AM/PM in my code:

const dateObj: any = dayjs('2021-02-05 12:00 AM').format('YYYY-MM-DD hh:mm A');

The output of dateObj is always "Invalid Date". If I remove the "AM" from the string it parses correctly. If I try this online tester for the same code, the output is

NaN-NaN-NaN NaN:NaN PM

Like with my dev environment, if I remove the AM, it's fine.

Any ideas?

EDIT: Working on Chrome and not Firefox...

Warplane answered 22/1, 2021 at 5:5 Comment(2)
I get 2021-02-05 12:00 AM in the tester you linked. I used dayjs('2021-02-05 12:00 AM').format('YYYY-MM-DD hh:mm A').Brieta
@Brieta Weird, here's a screenshot of my result: i.imgur.com/WrtSk9Z.png EDIT: Seems to be working on Chrome and not FF???Warplane
D
36

Issue on Firefox

If you deeply look at the implementation, you would see above day string going through the Day constructor: new Day('2021-02-05 12:00 AM'). Unfortunately FF doesn't support this support this day string format, but Chrome does.

Best approach

The dayjs documentation mentions:

For consistent results parsing anything other than ISO 8601 strings, you should use String + Format.

If you're still keen to use above format, you would have to use a plugin as mentioned here

Basically, you have to change as below to work in all browsers:

import customParseFormat from 'dayjs/plugin/customParseFormat'
import dayjs from "dayjs"

dayjs.extend(customParseFormat)

const yourDate = dayjs('2021-02-05 12:00 AM', 'YYYY-MM-DD HH:mm A')
Dealings answered 22/1, 2021 at 6:54 Comment(1)
This should be the default. Very misleading considering that the dayjs website's console extends this plugin. Great answer, thanks!Sassanid
K
2

You need a plugin:

  import dayjs from 'dayjs'
  import customParseFormat from 'dayjs/plugin/customParseFormat'
  
  dayjs.extend(customParseFormat)

Then it should work:

https://day.js.org/docs/en/plugin/custom-parse-format

Kop answered 1/12, 2023 at 11:59 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.