简体   繁体   English

将时区偏移量应用于js代码

[英]apply timezone offset to js code

I am trying to compare the current time to some timestring variables I have in my db. 我试图将当前时间与数据库中的一些时间字符串变量进行比较。

I had the following code working but the time on my server changed and now it no longer works. 我可以使用以下代码,但是服务器上的时间已更改,现在不再可用。

var d = new Date();
var day = d.getDate();
if ((day.toString()).length == 1){
    day='0'+day;
}
var month = d.getMonth()+1;
if ((month.toString()).length == 1){
    month='0'+month;
}


var mins = d.getMinutes()+100;
console.log("mins is " + mins);
var timeVar = (d.getHours() * 100) + mins;

//concatenated string version of the var
var currtime = year+month+day+timeVar;

I know if I call d.getTimezoneOffset(), I get -240 and that is exactly my issue, I am 4 hours off. 我知道如果我叫d.getTimezoneOffset(),我会得到-240,这正是我的问题,我要休息4小时。 But I cant apply that value in the right way to my code. 但是我不能以正确的方式将这个值应用于我的代码。

Right now my variable for currTime returns: 现在,我的currTime变量返回:

20150707242 but I need it to return 20150 7 072 2 42 20150707242但我需要它返回20150 7 072 2 42

Any help appreciated. 任何帮助表示赞赏。

UPDATE 更新

I was about to get the correct timeVar using: 我将使用以下方法获取正确的timeVar:

var d2 = new Date(new Date().getTime() + (d.getTimezoneOffset() * 1000));
var hrs2 = d2.getUTCHours();
var mins2 = d2.getUTCMinutes();

console.log("hrs2 = " + (hrs2+1) + " mins2 = "+ (mins2 + 4));

var actualHrs = hrs2+1;
var actualmins = mins2 +4;
var currtime = year+month+day+actualHrs+actualmins;

But now my issue exists with my day variable created as such: 但是现在我的问题存在,我的日变量创建为:

var d = new Date();
var day = d.getDate();
if ((day.toString()).length == 1){
    day='0'+day;
}

Because my time retrieved is 4 hrs ahead, it thinks my current day is tomorrow. 因为我的检索时间提前了4个小时,所以我认为今天是明天。

Can anyone help me get around this? 谁能帮我解决这个问题?

You can use var a = Date(timestamp) to generate the correct date oject, which is internally the number of millisecond from 01-01-1970. 您可以使用var a = Date(timestamp)生成正确的日期对象,该日期对象内部是从1970年1月1日开始的毫秒数。

Confronting two date object is a simple subtraction 面对两个日期对象是一个简单的减法

var a = new Date();
var b = new Date(timestring);
var delta = a - b // a signed integer

more on parsing dates from timestring 从时间字符串解析日期的更多信息

As you already did this 正如您已经做过的

var d2 = new Date(new Date().getTime() + (d.getTimezoneOffset() * 1000));

is kind of a good way to deal with your problem of timezones 是解决时区问题的一种好方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM