Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Need to display local times over DST transitions using Javascript Date Object

I am trying to output a series of times in hour (on the hour) intervals within Javascript (so inside a web browser such as Firefox). This series of times will overlap the short day (losing an hour in spring) and long day (gaining an hour in autumn). The output I'm looking for is in local time, i.e. with timezone and DST offsets applied. So for example, in the UK we have a missing hour from 01:00 to 01:59 on the short day such that the output would be:

00:00, 02:00, 03:00

And on the long day we have an extra hour from 01:00 to 02:00 such that the output would be:

00:00, 01:00, 01:00, 02:00, 03:00

I have already found these two brilliant answers that highlight some pitfalls and address part of my problem:

  • Daylight saving time and time zone best practices
  • Javascript Date objects and Daylight Savings Time

But the real difficulty is in making javascript aware of this missing and extra hour (so to speak) as identified in the second question mentioned above.

I think a potential solution to this would be to operate in UTC (aka GMT) and just do a conversion to local time but I'm struggling to see how I could do this.

Does anyone have any ideas about how to achive what I'm after?

like image 441
A. Murray Avatar asked Sep 05 '11 16:09

A. Murray


2 Answers

If you have a fixed timezone, the following javascript code seems to work (tested on the last chrome version and firefox 6) :

 // set the date to 11 / 04 / 2012 at 00:00 UTC
 var date = new Date(1331424000000);
 for(var i = 1; i <= 12; i++) {   
     $('.data-dston').append(' ' + date.getHours() + ':00, ');
     date = new Date(date.getTime() + 3600000)
 }

 // set the date to 04 / 11 / 2012 at 00:00 UTC
 var date = new Date(1351987200000);
 for(var i = 1; i <= 12; i++) {   
     $('.data-dstoff').append(' ' + date.getHours() + ':00, ');
     date = new Date(date.getTime() + 3600000)
 }

Here's a JSFiddle : http://jsfiddle.net/Vsd2A/3/ to see the code in action !

like image 71
krtek Avatar answered Oct 10 '22 03:10

krtek


Adapting what Krtek has come up with (for my timezone - UK) I now have the following:

// set the date to 27 / 03 / 2011 at 00:00 UTC
var date = new Date('27 Mar 2011 00:00');
for(var i = 1; i <= 12; i++)
{   
    $('.data-dston').append(' ' + date.getHours() + ':00, ');
    date.setTime(date.getTime() + 3600000);
}

// set the date to 30 / 10 / 2011 at 00:00 UTC
var date = new Date('30 Oct 2011 00:00');
for(var i = 1; i <= 12; i++)
{   
    $('.data-dstoff').append(' ' + date.getHours() + ':00, ');
    date.setTime(date.getTime() + 3600000)
}

Which has the benefit of not having to construct a new object on each iteration.

like image 34
A. Murray Avatar answered Oct 10 '22 01:10

A. Murray