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

烂漫一生 提交于 2019-12-22 05:25:07

问题


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?


回答1:


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 !




回答2:


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.



来源:https://stackoverflow.com/questions/7310560/need-to-display-local-times-over-dst-transitions-using-javascript-date-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!