我有一个特定时区的日期时间作为字符串,我想将其转换为本地时间。但是,我不知道如何在Date对象中设置时区。
例如,我有2013年2月28日东部时间晚上7点,然后我可以
var mydate = new Date();
mydate.setFullYear(2013);
mydate.setMonth(02);
mydate.setDate(28);
mydate.setHours(7);
mydate.setMinutes(00);
据我所知,我可以设置UTC时间或本地时间。但是,如何在另一个时区设置时间呢?
我尝试使用添加/减去UTC的偏移量,但我不知道如何对抗夏令时。我不确定我走的方向是否正确。
如何在javascript中将时间从不同的时区转换为本地时间?
我发现最受支持的方法是使用getTimezoneOffset来计算适当的时间戳,或者更新时间,然后使用正常的方法来获得必要的日期和时间。
var mydate = new Date();
mydate.setFullYear(2013);
mydate.setMonth(02);
mydate.setDate(28);
mydate.setHours(7);
mydate.setMinutes(00);
// ET timezone offset in hours.
var timezone = -5;
// Timezone offset in minutes + the desired offset in minutes, converted to ms.
// This offset should be the same for ALL date calculations, so you should only need to calculate it once.
var offset = (mydate.getTimezoneOffset() + (timezone * 60)) * 60 * 1000;
// Use the timestamp and offset as necessary to calculate min/sec etc, i.e. for countdowns.
var timestamp = mydate.getTime() + offset,
seconds = Math.floor(timestamp / 1000) % 60,
minutes = Math.floor(timestamp / 1000 / 60) % 60,
hours = Math.floor(timestamp / 1000 / 60 / 60);
// Or update the timestamp to reflect the timezone offset.
mydate.setTime(mydate.getTime() + offset);
// Then Output dates and times using the normal methods.
var date = mydate.getDate(),
hour = mydate.getHours();
EDIT
我以前在执行日期转换时使用UTC方法,这是不正确的。通过将偏移量添加到时间上,使用本地get函数将返回所需的结果。
试试这样的方法,
public static getTimezoneOffset(timeZone: string, date = new Date()): number {
const localDate = date.toLocaleString('fr', { timeZone, timeZoneName: 'long' });
const tz = localDate.split(' ');
const TZ = localDate.replace(tz[0], '').replace(tz[1], '').replace(' ', '');
const dateString = date.toString();
const offset = (Date.parse(`${dateString} UTC`) - Date.parse(`${dateString}${TZ}`)) / (3600 * 1000);
return offset;
}
这应该解决您的问题,请随时提供修复。该方法还将考虑给定日期的夏时制。
dateWithTimeZone = (timeZone, year, month, day, hour, minute, second) => {
let date = new Date(Date.UTC(year, month, day, hour, minute, second));
let utcDate = new Date(date.toLocaleString('en-US', { timeZone: "UTC" }));
let tzDate = new Date(date.toLocaleString('en-US', { timeZone: timeZone }));
let offset = utcDate.getTime() - tzDate.getTime();
date.setTime( date.getTime() + offset );
return date;
};
如何与时区和本地时间一起使用:
dateWithTimeZone("America/Los_Angeles",2019,8,8,0,0,0)
你可以在new Date()上指定一个时区偏移量,例如:
new Date('Feb 28 2013 19:00:00 EST')
or
new Date('Feb 28 2013 19:00:00 GMT-0500')
由于Date存储UTC时间(即getTime返回UTC), javascript将它们转换为UTC时间,当你调用toString之类的东西时,javascript将把UTC时间转换为浏览器的本地时区,并返回本地时区的字符串,即如果我使用UTC+8:
> new Date('Feb 28 2013 19:00:00 GMT-0500').toString()
< "Fri Mar 01 2013 08:00:00 GMT+0800 (CST)"
你也可以使用普通的getHours/Minute/Second方法:
> new Date('Feb 28 2013 19:00:00 GMT-0500').getHours()
< 8
(这个8意味着在时间转换为我的本地时间- UTC+8后,小时数是8。)