Jo Smo Jo Smo - 10 days ago 5
Javascript Question

How to check if the DST (Daylight Saving Time) is in effect and if it is what's the offset?

This is a bit of my JS code for which this is needed:

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


I want to get the datetime in ago, but if the DST is in use then the dates are off by 1 hour. I don't know how to check if the DST is in use or not.

How can i know when the daylight saving starts and ends?

Answer

The code given by this article will tell you whether Daylight Savings Time is in effect. It uses the fact that getTimezoneOffset returns a different value during DST and standard time, and compares the difference between the two. (for example New York returns -5 normally and -4 during DST)

Note that I have no idea as to the intricacies of international time zones, and have only tested that it returns correct results for my time zone.. but the code seems solid.

var today = new Date();
if (today.dst()) { alert ("Daylight savings time!"); }

Date.prototype.stdTimezoneOffset = function() {
    var jan = new Date(this.getFullYear(), 0, 1);
    var jul = new Date(this.getFullYear(), 6, 1);
    return Math.max(jan.getTimezoneOffset(), jul.getTimezoneOffset());
}

Date.prototype.dst = function() {
    return this.getTimezoneOffset() < this.stdTimezoneOffset();
}
Comments