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



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

我想知道如果没有Moment.JS这样的模块,我是否可以用JS实现这种转换?

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

"2021年1月3日晚上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";

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

//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());

最新更新