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.
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)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.