这是我的一点JS代码,这是需要的:

var secDiff = Math.abs(Math.round((utc_date-this.premiere_date)/1000));
this.years = this.calculateUnit(secDiff,(86400*365));
this.days = this.calculateUnit(secDiff-(this.years*(86400*365)),86400);
this.hours = this.calculateUnit((secDiff-(this.years*(86400*365))-(this.days*86400)),3600);
this.minutes = this.calculateUnit((secDiff-(this.years*(86400*365))-(this.days*86400)-(this.hours*3600)),60);
this.seconds = this.calculateUnit((secDiff-(this.years*(86400*365))-(this.days*86400)-(this.hours*3600)-(this.minutes*60)),1);

我想在“前”得到日期时间,但如果DST正在使用,那么日期是1小时。我不知道如何检查夏令时是否有效。

我怎样才能知道夏令时何时开始和结束?


当前回答

使用Date.toString()是否有问题。indexOf('Daylight Time') > -1

"" +新日期()

1月1日星期六100050 00:00:00 GMT-0500(美国东部标准时间)

"" +新日期(…)

5月01日100033 00:00:00 GMT-0400(东部夏令时)

这似乎与所有浏览器兼容。

其他回答

这个答案与公认的答案非常相似,但没有覆盖Date原型,并且只使用一个函数调用来检查日光节约时间是否有效,而不是两个。


这个想法是,由于没有国家遵守持续7个月的夏时制[1],在遵守夏时制的地区,1月份与UTC时间的偏移量将与7月份的偏移量不同。

虽然夏令时将时钟向前移动,但JavaScript总是在标准时间期间返回更大的值。因此,在1月和7月之间获取最小偏移量将获得夏令时期间的时区偏移量。

然后检查dates timezone是否等于该最小值。如果是,那么我们就是在夏令时;否则我们就不是了。

下面的函数使用这个算法。它接受一个日期对象d,如果夏令时在该日期有效,则返回true,如果不是则返回false:

function isDST(d) {
    let jan = new Date(d.getFullYear(), 0, 1).getTimezoneOffset();
    let jul = new Date(d.getFullYear(), 6, 1).getTimezoneOffset();
    return Math.max(jan, jul) !== d.getTimezoneOffset();    
}

js库在它的time对象上提供了一个. isdst()方法。

moment#isDST检查当前时刻是否属于夏时制。

moment([2011, 2, 12]).isDST(); // false, March 12 2011 is not DST
moment([2011, 2, 14]).isDST(); // true, March 14 2011 is DST

使用Date.toString()是否有问题。indexOf('Daylight Time') > -1

"" +新日期()

1月1日星期六100050 00:00:00 GMT-0500(美国东部标准时间)

"" +新日期(…)

5月01日100033 00:00:00 GMT-0400(东部夏令时)

这似乎与所有浏览器兼容。

你很接近了,但是有点差。你永远不需要计算你自己的时间,因为它是你自己的时钟的结果。它可以检测您是否在您的位置使用日光节约时间,但不能检测由偏移量产生的远程位置:

newDateWithOffset = new Date(utc + (3600000*(offset)));

This will still be wrong and off an hour if they are in DST. You need for a remote time account if they are currently inside their DST or not and adjust accordingly. try calculating this and change your clock to - lets say 2/1/2015 and reset the clock back an hour as if outside DST. Then calculate for an offset for a place that should still be 2 hours behind. It will show an hour ahead of the two hour window. You would still need to account for the hour and adjust. I did it for NY and Denver and always go the incorrect (hour ahead) in Denver.

我今天也遇到了同样的问题,但由于我们的夏令时开始和结束的时间与美国不同(至少从我的理解来看),我使用了稍微不同的路线。

var arr = [];
for (var i = 0; i < 365; i++) {
 var d = new Date();
 d.setDate(i);
 newoffset = d.getTimezoneOffset();
 arr.push(newoffset);
}
DST = Math.min.apply(null, arr);
nonDST = Math.max.apply(null, arr);

然后,您只需将当前时区偏移量与DST和非DST进行比较,以查看哪一个匹配。