2

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

Ashish Choubey
  • 407
  • 1
  • 5
  • 17
  • Probably a duplicate of [*Calculate Timezone offset only for one particular timezone*](https://stackoverflow.com/questions/61361914/calculate-timezone-offset-only-for-one-particular-timezone). There's no built–in way to create a Date in ECMAScript with values and assumed offset than for the host default timezone or UTC. That's it. The Date object itself has no timezone, it's UTC. The proposed [*Temporal* object](https://github.com/tc39/proposal-temporal) will do what you want. Until it arrives, use a library. – RobG Apr 22 '22 at 14:17

1 Answers1

0

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)
Samuel Olekšák
  • 389
  • 4
  • 12
  • Shows "Invalid Date" in Safari. Where is the part to select the location and time to initialise the Date? – RobG Apr 22 '22 at 14:12