Create time by keeping timezone in account in Javascript

Viewed 33

Let's say a user selects time as 7: 00 AM as time and time zone as "Africa/Blantyre" . I want to create a date object such that the value contains 7:00 AM of "Africa/Blantyre" and when the user changes the timezone to "Asia/Jakarta", the value that was captured for 7:00 AM "Africa/Blantyre" should be of timezone "Asia/Jakarta". It should not be 7:00 AM "Asia/Jakarta" but converted value of "Africa/Blantyre".

1 Answers

You can just store the time as a UNIX timestamp (number of seconds since UNIX epoch (1st of January 1970), this is independent from timezone) and store the user's current timezone independently. Then before displaying the time to the user you convert it from UNIX timestamp to their own timezone format, for example with Date.prototype.toLocaleString().

Just be careful getTime() returns milliseconds since UNIX epoch so it's UNIX timestamp * 1000.

const d1 = (new Date("2022-04-22 3:00 PM UTC+1")).getTime() // UTC+1 timezone

// store d1

const d2 = (new Date(d1)).toLocaleString('en-US', { timeZone: 'UTC' }) // UTC timezone
console.log(d2)

Related