添加或减去 javascript 日期的时区差异

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7403486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 02:09:11  来源:igfitidea点击:

add or subtract timezone difference to javascript Date

javascriptdate

提问by halliewuud

What is the best approach to add or subtract timezone differences to the targetTimevariable below. The GMT timezone values comes from the DB in this format: 1.00for London time, -8.00for Pacific time and so on.

targetTime下面的变量中添加或减去时区差异的最佳方法是什么。GMT 时区值以这种格式来自数据库:1.00伦敦时间、-8.00太平洋时间等。

Code looks like this:

代码如下所示:

date = "September 21, 2011 00:00:00";
targetTime = new Date(date);

回答by alexp

You can use Date.getTimezoneOffset which returns the local offset from GMT in minutes. Note that it returns the value with the opposite sign you might expect. So GMT-5 is 300 and GMT+1 is -60.

您可以使用 Date.getTimezoneOffset 以分钟为单位返回 GMT 的本地偏移量。请注意,它返回的值与您可能期望的符号相反。所以 GMT-5 是 300,GMT+1 是 -60。

var date = "September 21, 2011 00:00:00";
var targetTime = new Date(date);
var timeZoneFromDB = -7.00; //time zone value from database
//get the timezone offset from local time in minutes
var tzDifference = timeZoneFromDB * 60 + targetTime.getTimezoneOffset();
//convert the offset to milliseconds, add to targetTime, and make a new Date
var offsetTime = new Date(targetTime.getTime() + tzDifference * 60 * 1000);

回答by user2875462

Simple function that works for me:

对我有用的简单功能:

adjustForTimezone(date:Date):Date{
    var timeOffsetInMS:number = date.getTimezoneOffset() * 60000;
    date.setTime(date.getTime() - timeOffsetInMS);
    return date
}

回答by Marcos Lima

If you need to compensate the timezone I would recommend the following snippet:

如果您需要补偿时区,我会推荐以下代码段:

var dt = new Date('2018-07-05')
dt.setMinutes(dt.getMinutes() + dt.getTimezoneOffset())
console.log(dt)