How to parse times in local timezone?
Inputs with absolute time (other than ISO8601 with time zone offset) seem to be parsed as UTC. Here is a simple NodeJS 20.12.0 example for America/New_York time zone (UTC-4 for the date used below):
import 'any-date-parser'
const input = '7/11/2024 04:15:00 PM'
console.log('input:', input)
const date = Date.fromString(input)
console.log('date:', date)
console.log('toLocaleString:', date.toLocaleString())
Outputs:
input: 7/11/2024 04:15:00 PM
date: 2024-07-11T16:15:00.000Z
toLocaleString: 7/11/2024, 12:15:00 PM. # <-- I would like 04:15:00 PM
If the input were interpreted in local time zone, UTC time would be 20:15:00Z
I've tried appending a time zone offset to the input string, but I either get parsing errors, or the offset is interpreted as the time itself.
Is it possible to parse input times in the local time zone? So that:
Date.fromString(someDate.toLocaleString()) === someDate
Thanks!
After some digging, I see that 24hr format accepts an offset, but 12hr format apparently does not.
Hello @showaltb. Please see issue #40 for information about working with timezones and offsets.
Your other request, to parse offsets with AM/PM, now works in v2.1:
import parser from 'any-date-parser';
parser.attempt('7/11/2024 04:15:00 PM -04:00');
{
hour: 16, // 4pm
minute: 15,
second: 0,
offset: -240, // -04:00
month: 7,
day: 11,
year: 2024
}
Note that when the server or browser uses the en-GB locale, the date above will be interpreted as Nov 7. To use a locale different from the system locale, you can pass it as a second argument to parser.attempt or Date.fromString.
import parser from 'any-date-parser';
parser.attempt('7/11/2024 04:15:00 PM -04:00', 'en-GB');
{
hour: 16,
minute: 15,
second: 0,
offset: -240,
day: 7,
month: 11,
year: 2024
}
// or
Date.from('7/11/2024 04:15:00 PM -04:00', 'en-GB');