I’d like to be able to parse a date/time given by the user into a Date (or luxon DateTime object). I don’t know the user’s format beforehand. They’ll likely be copy-pasting it from another source so I’d prefer not to force a particular format.
Perl has Date::Parse exactly for this and it works brilliantly.
What is the JavaScript equivalent?
The timestamp could come e.g. in any of these formats, or others:
- Fri Sep 20, 2024 04:07PM
- 2024-09-22 04:07:00-0700
- 2024-09-20 04:07:00
- 2024-09-20 04:07
- 9/20 4:07
- 20/9 4:07
- 4:07
- Sep 20, 4:07
- Sep 20
When there is ambiguity, I’d like the last instance, so e.g. 4:07
refers to the last time it was 4:07. And for e.g. “2/3” which could be Mar 2 or Feb 3, just pick one of them.
-
luxon seems to be king of the hill at the moment. Its
DateTime.fromFormat
does it perfectly. It can take azone
as one of its options, and if the given format and string doesn’t contain time zone information, the zone parameter controls which time zonefromFormat
will interpret the time stamp in. But withDateTime.fromFormat
I’m locked into having to specify a fixed format known beforehand.But I apparently can’t get luxon to try its best without a format string. Is there such a thing as moment-guess for luxon or other ways to get luxon to do this?
-
new Date(str)
Date.new() on Chrome does a pretty good job of guessing the Date from any string you throw at it, but
Apr 1
gets interpreted asSun Apr 01 2001 00:00:00 GMT+0200 (Central European Summer Time)
which has two problems: 2001 is not the most recent and there is no way to tellnew Date()
which time zone to use. It always uses the local time zone. Also, apparently implementations are inconsistent -
moment.js is deprecated
-
Temporal isn’t here yet.
-
date-fns’s
parse
needs a format string -
js-joda’s
DateTimeFormatter.ofPattern
needs a format string -
dayjs either needs a format string or assumes ISO 8601 format.