Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
455 views
in Technique[技术] by (71.8m points)

javascript - dayjs() telling me invalid date for this date string

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

question from:https://stackoverflow.com/questions/65839590/dayjs-telling-me-invalid-date-for-this-date-string

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

As the document mentioned as below:

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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...