0

I need to convert a Date string to date object in javascript. What I receive is something like:

utc='2021-02-03T02:44:51.118Z'.  # time in utc

local='2021-02-03T12:44:51.118Z' # time in local timezone

for above two strings, each of which represent a different timezone. How can I create a Date object from them to represent the right timezone? Ideally I'd like to convert them to epoch format but don't know how to calculate offset correctly.

I have looked at getTimezoneOffset method but it doesn't consider daylight saving time.

Joey Yi Zhao
  • 37,514
  • 71
  • 268
  • 523
  • This answer should help: https://stackoverflow.com/questions/56316657/how-to-update-the-time-every-second-using-setinterval-without-the-time-flash/56317035#56317035 -- if not that one, this one: https://stackoverflow.com/questions/65818270/changing-list-of-time-zone-offset-numbers-to-current-times-with-javascript/65818776#65818776 – Randy Casburn Feb 03 '21 at 02:37
  • You can get current timestamp using `+ new Date()`. See [this question](https://stackoverflow.com/a/221297/9416618). – Maytha8 Feb 03 '21 at 03:39
  • You can convert the UTC date into a timestamp directly using `new Date("place date here").getTime()` because the dates and times you're using are formatted in ISO 8601 format. Note: this will return it in millisecond resolution. To get a proper timestamp (in seconds), use this instead: `Math.floor(new Date("place date here").getTime() / 1000)`. See [here](https://stackoverflow.com/a/9873379/9416618). You must use the UTC/GMT time to get a correct timestamp. – Maytha8 Feb 03 '21 at 03:43

1 Answers1

1

You can use Date object and method toLocaleString().

When you use the string '2021-02-03T02:44:51.118Z' or '2021-02-03T12:44:51.118Z', they are all UTC time.

When you use the string '2021-02-03T12:44:51.118+10:00', it is time zone +10:00 (Dumont d'Urville Station).

To convert UTC to local time zone, use this code:

let time = "2021-02-03T02:44:51.118Z"

let t = new Date(time)
console.log(t.toLocaleString("en-US", {timeZone: "Antarctica/DumontDUrville"}));

To convert local time to UTC, use this code:

let local = "2021-02-03T12:44:51.118+10:00"
let t = new Date(local)
console.log(t.toLocaleString("en-US", {timeZone: "UTC"}));

Note:

  • Z means "zero hour offset" also known as "Zulu time" (UTC)
  • Can see list of local timeZone code at here
dqthe
  • 683
  • 5
  • 8