我有一个特定时区的日期时间作为字符串,我想将其转换为本地时间。但是,我不知道如何在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中将时间从不同的时区转换为本地时间?


当前回答

遇到了同样的问题,用了这个吗

Console.log(Date.parse(“Jun 13, 2018 10:50:39 GMT+1”));

它将返回毫秒,你可以检查有+100 timzone初始化英国时间 希望能有所帮助!!

其他回答

尝试:date-from-timezone,它通过本地可用的Intl.DateTimeFormat来解析预期的日期。

我在我的一个项目中使用这种方法已经有几年了,但现在我决定把它作为一个小的OS项目发布:)

简单,支持Node.JS

传入时区与UTC时间的偏移量

function initDateInTimezone(offsetHours) {
  const timezoneOffsetInMS = offsetHours * 60 * 60000;
  let d = new Date().getTimezoneOffset() * 60000 + timezoneOffsetInMS;
  const date = new Date(new Date().getTime() - d);
    return date
}

对于Ionic用户来说,我遇到了麻烦,因为. toisostring()必须与html模板一起使用。

这将获取当前日期,但当然也可以添加到先前选定日期的答案中。

我用这个解决了它:

date = new date (); public currentDate: any = new Date(this.date.getTime() - this.date.getTimezoneOffset()*60000).toISOString();

*60000表示UTC -6,即CST,因此无论需要什么时区,数字和差异都可以更改。

你可以在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。)

这里有几个工作答案,但不知为何,他们中的很多人似乎让你到字符串,但不是回到一个日期对象,你开始,所以这里是我的简单的非函数采取如何在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.

希望这对其他人有所帮助(如果你找到了下面的答案!)