我有datestring,想象这是2021-03-05T18:23:42。
我需要从这里创建new Date(),但new Date('2021-03-05T18:23:42')将返回当前用户浏览器的时区中的日期。但是我需要在Grinvich (基本)时区中创建new Date()。18:23 (在当前情况下),精确到Grinvich时区。我的意思是,当纽约某处的用户打开我的浏览器时,她/他将看到的不是字符串中的18:23,而是13:23。因为在纽约市有GTM-5。如果用户在乌克兰打开它,她/他将看到20:23,因为在乌克兰有GMT+2。
该怎么做呢?
发布于 2021-03-06 06:57:30
所以问题是遗漏了Z字母。
有特殊的标准化日期字符串格式,其格式为。没有时区。只有一个时区,这个时区是Z (zulu,Grinvich)。
所以..。在任何编程语言中,当我们将任何数据转换为ISO字符串格式时,然后自动执行下一步操作
将我们的日期转换为Grinwich timezone
和。当我们调用new Date('dateString')构造函数时,它开始读取日期,如果它(浏览器)不知道一些东西,那么它(浏览器)就默认地设置一些东西。
在我的例子中,我发送给浏览器的字符串就像这里的"2021-03-05T18:23:42"是年、月、日、小时、分钟。但是没有时区。因此,当浏览器读取此字符串时,他默认设置当前用户的时区。但。当我加上'Z‘时(我的意思是字符串变成了"2021-03-05T18:23:42Z",然后我对浏览器说:“嘿,浏览器,这是Grinvich写的2021 03 05 18:23”。当我问浏览器时
const date = new Date("2021-03-05T18:23:42Z") // pay attention at Z in the end,浏览器做两件事
知道生命中的这个时刻(时间)被Grinvich
我很高兴,希望你也是:)
发布于 2021-03-06 03:30:09
您可以在Date实例上调用toLocaleTimeString并指定timeZone。别忘了用祖鲁语(Z)时区说明符解析它。
注意:在维基百科上查看List of tz database time zones,以获得潜在时区标识符的列表。
const
lang = 'en-US', // Localization setting
timestamp = '2021-03-05T18:23:42Z', // Note the 'Z' at the end
date = new Date(timestamp),
setText = (selector, text) => document.querySelector(selector).textContent = text,
displayDate = (date, lang, options = {}) => date.toLocaleTimeString(lang, options),
displayLocalDate = date => displayDate(date, lang),
displayDateGMT = date => displayDate(date, lang, { timeZone:'GMT' }),
displayDateUkraine = date => displayDate(date, lang, { timeZone:'Europe/Kiev' });
setText('#localDate', displayLocalDate(date));
setText('#date', displayDateGMT(date));
setText('#date-ukraine', displayDateUkraine(date));.grid {
display: grid;
grid-auto-flow: row;
grid-template-columns: 1fr 2fr;
grid-row-gap: 0.5em;
width: 14em;
}
label {
display: inline-block;
font-weight: bold;
}
label:after {
content: ':';
}<div class="grid">
<label>Local </label> <span id="localDate"></span>
<label>GMT </label> <span id="date"></span>
<label>Ukraine</label> <span id="date-ukraine"></span>
</div>
https://stackoverflow.com/questions/66498007
复制相似问题