Javascript

Javascript Check For Daylight Saving

Trying to work out the correct DateTime offset of a visitor can be tricky, the easiest way of doing this would be with JavaScript. You can find out the visitors DateTime information by using the JavaScript Date object.

var today = new Date();

Then to get the current timezone offset you can use the method getTimezoneOffset().

var today = new Date();
var currentOffset = today.getTimezoneOffset();

This will return the amount of minutes the current timezone is offset from GMT. Therefore to get the offset in hours you'll need to divide by 60.

var today = new Date();
var currentOffsetInHours = (today.getTimezoneOffset() / 60);

But the offset could be different depending on the time of the year you are trying to access this information. For example the browser will know if the given timezone is in daylight saving or not so if the visitor accessed the page in January the offset could be different than when accessing the page in July.

First we need to create a function to return the largest of the offsets based on January and July.

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

The getTimezoneOffset() method will return the offset in minutes and will reverse the offset sign therefore if the offset is GMT+1 getTimezoneOffset() will return -60. In my example based on London timezone, the January offset will equal 0 whereas the July offset will equal -60.

jan.getTimezoneOffset() = 0

jul.getTimezoneOffset() = -60

The return of the new stdTimezoneOffset function will return the highest number of offset, this being the January offset of 0.

Then we compare the return of the stdTimezoneOffset function with the current offset. If the current offset is lower then we know that it's currently using daylight savings time.

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

Then we simply need to use the dst() method on the Date object.

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

var date = new Date();

if(date.dst())
{
  console.log('Yes');    
} else {
  console.log('No'); 
}

Code source: http://javascript.about.com/library/bldst.htm

See the Pen Is DST JavaScript by Paul (@paulund) on CodePen.

Back to top

Learn how to code with Treehouse

  • Learn projects with access to 1000+ videos
  • Practice live with our Code Challenge Engine
  • Get help in our members-only forums

Start with a 7 day free trial