TimeZone 选项在 Intl.DateTimeFormat() 中究竟做了啥
Posted
技术标签:
【中文标题】TimeZone 选项在 Intl.DateTimeFormat() 中究竟做了啥【英文标题】:What exactly does the timeZone option do in Intl.DateTimeFormat()TimeZone 选项在 Intl.DateTimeFormat() 中究竟做了什么 【发布时间】:2020-09-21 02:01:09 【问题描述】:我很难理解Intl.DateTimeFormat()
方法中的timeZone
选项究竟做了什么。我还找不到这方面的深入资源。任何解释将不胜感激。
背景:我们需要在前端显示后端服务器的时间戳,并且时区偏移存在一些问题。目前,我认为根据本地客户端时间显示正确时间的解决方案如下:
Intl.DateTimeFormat('en-GB',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZone: 'GMT'
).format(timestamp)
我不完全明白,为什么我需要通过选项 timeZone: 'GMT' for "Greenwich Mean Time' 来获取前端的正确时间。
【问题讨论】:
日期对象是时区感知的。当您显示日期时,出于显而易见的原因,您需要选择时区。我不完全确定你的疑问是什么。 【参考方案1】:时区用于计算当地时间:
const timeZones = [
"GMT",
"Europe/Madrid",
"Asia/Tokyo"
];
const timestamp = new Date();
let displayDate;
for (timeZone of timeZones)
displayDate = Intl.DateTimeFormat('en-GB',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
timeZone: timeZone
).format(timestamp);
console.log("%s @ %s", displayDate, timeZone);
【讨论】:
感谢您的解释。我还有一个问题:如果我不指定时区,运行时环境将引入其时区,从而为时间戳添加一个偏移量,否则将对应于 GMT 时间(没有偏移量?)。 这并不是 javascript 中日期的确切工作方式。Date
对象指向一个准确的(绝对)时刻(我不知道内部格式,也许它只是一个 Unix 时间,但我在推测)。每当需要(并考虑)时区时,运行时需要生成(相对)本地时间。以上是关于TimeZone 选项在 Intl.DateTimeFormat() 中究竟做了啥的主要内容,如果未能解决你的问题,请参考以下文章
未来日期/年份的 Java 夏令时 (TimeZone/ZoneId) 支持
date_default_timezone_get() — 取得一个脚本中所有日期时间函数所使用的默认时区
Warning: date(): It is not safe to rely on the system's timezone settings.
pycharm连接mysql报错!Server returns invalid timezone. Go to 'Advanced' tab and set 'serverTi