JavaScript: How to parse time of different timezones, considering daylight time
How can I to parse times from different time zones?
JavaScript can do it, as shown in the code above:
process.env.TZ = "Asia/Jerusalem" // supported on Node v13+
new Date("2022-01-23 10:00").toString() // 10:00 GMT+02 (Israel Standard Time)
new Date("2022-07-23 10:00").toString() // 10:00 GMT+03 (Israel Daylight Time)
process.env.TZ = "Australia/Melbourne"
new Date("2022-01-23 10:00").toString() // 10:00 GMT+11 (Australian Eastern Daylight Time)
new Date("2022-07-23 10:00").toString() // 10:00 GMT+10 (Australian Eastern Standard Time)
But, how can it be done in less hacky way then changing the process.env.TZ
?
Clarification: The requirement is to convert local time to UTC, not the other way around.
Converting UTC to local is easy:
new Date().toLocaleString("iso", { timeStyle:"full", timeZone:"America/New_York" })
Solution 1:
If you just want the offset of a timezone, you can take the IANA name for your timezone and pass it through to the date format like so:
const getOffset = (date, timezone) => -new Date(date).toLocaleString([], {timeZone: timezone, timeZoneName: 'shortOffset'}).match(/(?<=GMT|UTC).+/)[0]*60;
console.log(getOffset("2022-01-23 10:00", 'Asia/Jerusalem'))
console.log(getOffset("2022-07-23 10:00", 'Asia/Jerusalem'))
console.log(getOffset("2022-01-23 10:00", 'Australia/Melbourne'))
console.log(getOffset("2022-07-23 10:00", 'Australia/Melbourne'))