Sunday, May 1, 2011

Make a date object take timezone into consideration

I'm using the following piece of code:

$.log('Ending time: ' + ending_time);
$.log('Now: ' + new Date());
$.log('Difference: ' + new Date(ending_time - new Date()));

The output is the following:

Ending time: Thu Apr 23 2009 14:31:29 GMT+0200
Now: Thu Apr 23 2009 11:56:02 GMT+0200
Difference: Thu Jan 01 1970 03:35:26 GMT+0100

I'm using the "difference" to display how many hours and minutes there are left until ending_time, but because of the timezone differences, I get the wrong time (offset by one hour.) So is there any neat way of calculating the difference taking timezones into account?

From stackoverflow
  • You should be able to use the getTimezoneOffset function.

    Check it out here.

  • You can use the following:

    (new Date()).getTimezoneOffset()
    

    which will give you the timezone offset of the client's browser in minutes. Of course you also need to know the timezone offset of ending time.

  • You are no longer dealing with a date, so don't convert it to one. You have a time difference, which doesn't have a time zone for instance. The result should be in milliseconds, so perform the appropriate math to get minutes, hours, days, or possibly all of the above as needed.

    Deniz Dogan : That's exactly what I did. I guess I was too lazy to do the manual calculating myself...

0 comments:

Post a Comment