简体   繁体   English

将从服务器收到的 UTC 日期转换为 Javascript 中的本地时区日期

[英]Convert UTC date received from server to local timzone date in Javascript

Working with Javascript, I want to convert the UTC date received from the server to the local timezone date object in the client's browser.使用 Javascript,我想在客户端的浏览器中将从服务器接收到的 UTC 日期转换为本地时区日期 object。

Which function/code do I have to use in Javascript?我必须在 Javascript 中使用哪个功能/代码? For example, converting this UTC date: '2021-01-20T17:40:35'.例如,转换此 UTC 日期:'2021-01-20T17:40:35'。

The format '2021-01-20T17:40:35' is supported by ECMA-262, but without a timezone it's parsed as local. ECMA-262 支持格式“2021-01-20T17:40:35”,但没有时区,它被解析为本地。 If you want it parsed as UTC just add "Z" to set the offset to 0, so:如果您希望将其解析为 UTC,只需添加“Z”将偏移量设置为 0,因此:

new Date('2021-01-20T17:40:35' + 'Z')

parses the string as UTC.将字符串解析为 UTC。 Then the local date and time is returned by the various get* methods , or just toString .然后本地日期和时间由各种get*方法返回,或者只是toString

However, if you want a truely robust function, parse it manually, eg但是,如果您想要一个真正强大的 function,请手动解析它,例如

// Get the parts
let [Y, M, D, H, m, s] = '2021-01-20T17:40:35'.split(/\D/);
// Treat as UTC
let date = new Date(Date.UTC(Y, M-1, D, H, m, s));

There are many questions on formatting dates.关于格式化日期有很多问题。 Any toString method that doesn't include the characters "UTC" or "ISO" will return local values based on the host system's regional settings for timezone and DST.任何不包含字符“UTC”或“ISO”的toString方法都将根据主机系统的时区和 DST 区域设置返回本地值。

Eg例如

 let [Y, M, D, H, m, s] = '2021-01-20T17:40:35'.split(/\D/); let date = new Date(Date.UTC(Y, M-1, D, H, m, s)); // Formatted as specified in ECMA-262 console.log(date.toString()); // So-called "locale aware" string, based on language console.log(date.toLocaleString()); // In another timezone for Antarctica/McMurdo console.log(date.toLocaleString('default', {timeZone: 'Antarctica/McMurdo', timeZoneName: 'short'}));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM