添加或减少时区差异到javascript日期 [英] add or subtract timezone difference to javascript Date

查看:72
本文介绍了添加或减少时区差异到javascript日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

看下面的代码。向下面的 targetTime 变量添加或减少时区差异的最佳方法是什么? GMT时区的值来自DB,格式为: 1.00 伦敦时间, -8.00

Take a look at the code below. What is the best approach to add or subtract timezone differences to the targetTime variable below. The GMT timezone values comes from the DB in this format: 1.00 for London time, -8.00 for Pasific time and so on.

代码如下所示:

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


推荐答案

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

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.

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);

这篇关于添加或减少时区差异到javascript日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆