9

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...

Dan
  • 1,163
  • 3
  • 14
  • 28
  • 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')`. – Ouroborus Jan 22 '21 at 05:20
  • @Ouroborus Weird, here's a screenshot of my result: https://i.imgur.com/WrtSk9Z.png EDIT: Seems to be working on Chrome and not FF??? – Dan Jan 22 '21 at 05:21

1 Answers1

28

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')
Crayons
  • 1,906
  • 1
  • 14
  • 35
tmhao2005
  • 14,776
  • 2
  • 37
  • 44
  • This should be the default. Very misleading considering that the dayjs website's console extends this plugin. Great answer, thanks! – adelriosantiago Jun 14 '23 at 13:55