Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript dates: what is the best way to deal with Daylight Savings Time?

In a previous question I wrote about a javascript date function that was mysteriously stopping on 11/07/101. Thanks to the stackoverflow users I was told my problem is Daylight Savings Time. Javascript date, is this my error or did I find a bug?

So my last question on this is what is the recommended approach in Javascript to deal with Daylight Savings Time?

Is http://code.google.com/p/datejs/ the best approach to solve this?

like image 785
davidjhp Avatar asked Nov 05 '10 21:11

davidjhp


People also ask

How does Javascript handle daylight Savings time?

We can solve this problem in simple 5 steps. Obtain the current UTC time, by adding the local time zone offset to the local time. Obtain the destination city's UTC offset in hours, convert it to milliseconds and add it to UTC time. Convert final msec value into new Date string.

What is the function to offset the date for daylight saving in time series Javascript?

To check if DST (Daylight Saving time) is in effect: Use the getTimezoneOffset() method to get the timezone offset for the 2 dates.

How does UTC handle daylight Savings?

The switch to daylight saving time does not affect UTC. It refers to time on the zero or Greenwich meridian, which is not adjusted to reflect changes either to or from Daylight Saving Time.


1 Answers

The best way is not to deal with DST. Use the UTC methods and you won't have to worry about crossing a DST boundary, or any other timezone discontinuity (locale timezone rules can change for more reasons than just DST).

var timestamp= Date.UTC(2010, 10-1, 31, 0, 0, 0); // zero-based month: 9->october
var nextday= new Date(timestamp+86400000); // add one day
var ymd= [
    nextday.getUTCFullYear(),
    nextday.getUTCMonth()+1, // zero-based month
    nextday.getUTCDate()
].join('-');
alert(ymd); // 2010-11-1

If the above had been done with new Date(2010, ...) and getDate() etc, it'd return 2010-10-31, the day add failing due to the DST change (in my region, anyway).

It is a pity that the ‘default’ most-obvious methods in Date are about local time, especially since JavaScript provides so very little context to scripts on what ‘local time’ actually is. UTC is a more stable proposition.

like image 54
bobince Avatar answered Oct 10 '22 01:10

bobince