Timezones in JS Date Pickers

Datepickers on the surface seem pretty simple when it comes to JavaScript, you add a datepicker to your website, the users clicks on a date and voila! A date object is set on the exact day.

But there is a hidden problem with these. Namely, dealing with time zones.

When you pick a date in most datepickers(ex- JQuery UI datepicker, Bootstrap Datepickers or even the default Datepickers in supported browsers), an entire Javascript Date object is created. These Date object behind the scenes are created using a UNIX timestamp which represent a set time as a difference from 1970 Jan 1st in milliseconds.

Even if we, as developers are only concerned about picking a date, a datepicker will have to decide a time to go with this date as well. This is where the problems arise. The default behaviour of most datepickers is to set 0000h on the selected day and the selected time-zone.

For example, if you were to pick 25th of April 2005 when you are is in Sri lanka, the date picker will select generate a complete date object with the timezone offset included.

i.e. the time selected will be 25th April 2005, at 0000h, +0530(IST offset).

This will work fine as long as you don’t convert it to another timezone. If you have multiple users, you will need to keep the times in a common format. Most often use format is UTC. To convert the above date to UTC, we simply remove the time offset.

This is where the problem comes in. When we reduce 0530 as the offset, we are left with a day that was on a previous date. When we convert IST 00:00 on 25th of April 2005 in to UTC, we get UTC 18:30 on 24th of April 2005. Which is off by one day!

While this is theoretically correct, there are some instances where the user expects the date to remain the same regardless of what timezone they are in. A common example would be a Date of Birth. While it might be theoretically correct to say that your date of birth is different in another timezone, you don’t expect that behaviour. You want that date to be consistent.

So what’s the solution to this? The most common method is to convert the date to UTC before saving the value. In JS, we can get the timezone offset and make the needed calculations to get the ‘correct’ date (ie- date we would get if we were in the UTC timezone)