【问题标题】:Dealing with offset changes in an attempt to display date correctly处理偏移量变化以尝试正确显示日期
【发布时间】:2021-02-09 04:52:21
【问题描述】:
我正在做一个项目,我需要显示一个时间戳。我将时间保存在 UTC 格式的数据库中。假设我所在地区的偏移量是 -4 小时(假设我处于夏令时),所以当我将时间输入数据库时,它会提前 4 小时输入。现在是冬天,偏移量是 -3 小时。当我将信息从数据库中拉回并将其更改回标准时间时,时间仅增加了 3 小时——而不是 4 小时。因此,所有项目的显示时间都比应有的时间早了一小时。所以我的问题是 - 有一种方法可以知道信息输入数据库时某个区域的确切偏移量?
【问题讨论】:
标签:
javascript
mysql
datetime
timezone-offset
【解决方案1】:
由于您从 UTC 日期和时间开始,您可以使用带有选项的 Intl.DateTimeFormat constructor 来获取特定 IANA representative location 的时区偏移量。
例如
function getOffset(s, location) {
let getTz = lang =>
new Intl.DateTimeFormat(lang,{
timeZone: location, timeZoneName:'short'
}).formatToParts(new Date(s)).reduce((acc, part) => {
if (part.type == 'timeZoneName') {
acc.tz = part.value;
} return acc;
}, Object.create(null)).tz;
let offset = getTz('en');
return (/\d/.test(offset)? offset : getTz('fr')).replace(/^[a-z]+/i, '');
}
let s = '2020-10-27T00:16:25.867Z';
console.log(`At ${s} the offset in these places is:`);
['America/New_York',
'Europe/Paris',
'Australia/Broken_Hill',
'Pacific/Apia',
'Pacific/Chatham'
].forEach(loc => console.log(`${loc}: ${getOffset(s, loc)}`));
请注意,如果使用的语言与主机的默认语言匹配,则返回时区的短名称。如果不匹配,则返回为 UTC±H:mm 或 GMT±H:mm,其中仅在需要时才包含分钟。所以该函数首先尝试 en,如果这不起作用,则使用 fr。我还没有找到 en 和 fr 返回缩写而不是偏移量的地方。