Timezones in JS Date Pickers
But there is a hidden problem with these. Namely, dealing with time zones.
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)