将UTC转换为特定时区时间Javascript

时间:2021-01-06 04:07:56

标签: javascript

目前,我正在后端使用 Moment.js 将 UTC 时间转换为特定时区的时间。它允许我将 2021-01-04T01:20:00Z 转换为 2021-01-03T20:20:00-05:00 以用于 America/toronto 时区。

我想知道我是否可以在没有 Moment.js 等模块的情况下用 JS 实现这种转换?

2 个答案:

答案 0 :(得分:1)

new Date('2021-01-04T01:20:00Z').toLocaleString('en-US', {timeZone: 'America/Toronto'})

“1/3/2021,晚上 8:20:00”

options = {
  year: 'numeric', month: 'numeric', day: 'numeric',
  hour: 'numeric', minute: 'numeric', second: 'numeric',
  hour12: false,
  timeZone: 'America/Toronto'
};
new Date('2021-01-04T01:20:00Z').toLocaleString('en-US', options)

new Intl.DateTimeFormat('en-US', options).format(new Date('2021-01-04T01:20:00Z'))

“2021 年 1 月 3 日,20:20:00”

options = {
  year: 'numeric', month: 'numeric', day: 'numeric',
  hour: 'numeric', minute: 'numeric', second: 'numeric',
  hour12: false,
  timeZone: 'America/Toronto',
  timeZoneName: 'short'
};
new Intl.DateTimeFormat('en-US', options).format(new Date('2021-01-04T01:20:00Z'))

“2021 年 1 月 3 日,美国东部时间 20:20:00”

答案 1 :(得分:1)

这是一个非常可重用的解决方案。

//Adds the toIsoString() function to the date object
Date.prototype.toIsoString = function() {
    var tzo = -this.getTimezoneOffset(),
        dif = tzo >= 0 ? '+' : '-',
        pad = function(num) {
            var norm = Math.floor(Math.abs(num));
            return (norm < 10 ? '0' : '') + norm;
        };
    return this.getFullYear() +
        '-' + pad(this.getMonth() + 1) +
        '-' + pad(this.getDate()) +
        'T' + pad(this.getHours()) +
        ':' + pad(this.getMinutes()) +
        ':' + pad(this.getSeconds()) +
        dif + pad(tzo / 60) +
        ':' + pad(tzo % 60);
}

//Creates a date object with the utc supplied, which automatically gets translated to your timezone
var localISOTime = new Date('2021-01-04T01:20:00Z');

//Outputs the date in ISO format with the timezone extension
console.log(localISOTime.toIsoString());

相关问题