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


当前回答

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

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

我用这个解决了它:

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

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

其他回答

我知道这3年太晚了,但也许它可以帮助其他人,因为除了moment-timezone库之外,我还没有找到任何类似的东西,这与他在这里要求的不完全相同。

我为德国时区做了类似的事情, 这有点复杂,因为日光节约时间和闰年,你有366天。

它可能需要与“isDaylightSavingTimeInGermany”函数做一些工作,而不同的时区在不同的日光节约时间发生变化。

不管怎样,看看这个页面: https://github.com/zerkotin/german-timezone-converter/wiki

主要方法有: convertLocalDateToGermanTimezone convertGermanDateToLocalTimezone

我已经努力记录了它,所以它不会那么令人困惑。

这应该解决您的问题,请随时提供修复。该方法还将考虑给定日期的夏时制。

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)

尝试使用npm中的ctoc。 https://www.npmjs.com/package/ctoc_timezone

它有简单的功能来改变时区(大多数时区大约400)和你想要显示的所有自定义格式。

我不知道为什么所有这些答案都如此复杂。在本地/所需时区中创建仅限日期的日期时,只需使用YYYY-MM-DD ZZZ。

创建一个本地日期:

var myDate = new Date('2022-11-29 CST')

日期将以UTC格式存储在存储器中,很好。

从存储中获取日期并显示为本地:

myDate.toLocaleDateString()

11/29/2022

我发现最受支持的方法是使用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函数将返回所需的结果。