这是我的一点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原型,并且只使用一个函数调用来检查日光节约时间是否有效,而不是两个。
这个想法是,由于没有国家遵守持续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