我有一个特定时区的日期时间作为字符串,我想将其转换为本地时间。但是,我不知道如何在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中将时间从不同的时区转换为本地时间?
我知道这3年太晚了,但也许它可以帮助其他人,因为除了moment-timezone库之外,我还没有找到任何类似的东西,这与他在这里要求的不完全相同。
我为德国时区做了类似的事情,
这有点复杂,因为日光节约时间和闰年,你有366天。
它可能需要与“isDaylightSavingTimeInGermany”函数做一些工作,而不同的时区在不同的日光节约时间发生变化。
不管怎样,看看这个页面:
https://github.com/zerkotin/german-timezone-converter/wiki
主要方法有:
convertLocalDateToGermanTimezone
convertGermanDateToLocalTimezone
我已经努力记录了它,所以它不会那么令人困惑。
试试这样的方法,
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;
}
这里有几个工作答案,但不知为何,他们中的很多人似乎让你到字符串,但不是回到一个日期对象,你开始,所以这里是我的简单的非函数采取如何在JS日期更改时区:
var TZ='Australia/Brisbane'; //Target timezone from server
var date = new Date(); //Init this to a time if you don't want current time
date=new Date(Date.parse(date.toLocaleString("en-US", {timeZone: TZ})));
//Just a clarification on what happens
// 1) First new Date() gives you a Date object at current time in the clients browser local timezone
// 2) .toLocaleString takes that time, and returns a string if time in the target timezone
// 3) Date.parse converts that new string to a Unix epoch number
// 4) new Date() converts the Unix epoch into a Date object in the new TimeZone.
// Now I can use my usual getHours and other Date functions as required.
希望这对其他人有所帮助(如果你找到了下面的答案!)