JavaScript dates and timezone offsets

Working with dates can be problematic when handling dates returned by a remote server. They were returned in GMT format, but when displayed on a page, the time was either ahead or behind (depending on which timezone you are in). For example, if you have the date returned via JSON:

var dates = {"StartDate": new Date(1216944000000),"EndDate": new Date(1217030399000)}

So the date now has the timezone offset added:

dates.StartDate = Fri Jul 25 2008 01:00:00 GMT+0100 (GMT Standard Time)
dates.EndDate = Sat Jul 26 2008 00:59:59 GMT+0100 (GMT Standard Time)

So now, to take into account the timezone offset, getTimezoneOffset() can be used, along with setMinutes() and getMinutes()

dates.StartDate.setMinutes(dates.StartDate.getTimezoneOffset() + dates.StartDate.getMinutes());
dates.EndDate.setMinutes(dates.EndDate.getTimezoneOffset() + dates.EndDate.getMinutes());

For a useful JavaScript library for working with dates (it extends the native Date object), check out Datejs. 30kb download, under an MIT open source license.

There is also another library, a smaller download (so slightly less functionality) available with the jQuery datePicker plugin - http://code.google.com/p/jqueryjs/source/browse/trunk/plugins/datePicker/v2/demo/date.js, under a dual MIT / GPL license. For more localisations (as well as string and array manipulation), visit http://code.google.com/p/jqueryjs/source/browse/trunk/plugins/methods. Note: jQuery is not required for these libraries to work.

Comments

Popular posts from this blog

Select box manipulation with jQuery

iTextSharp: Generating a Basic PDF file (ASP.NET/C#)

Popup Window Countdown (JavaScript)