0

I've been having a very rough time with dealing with Timzones and dates selected in DatePickers. And I'm talking about a scenario where we are not interested in a time component (think Date of Birth).

Most of the DatePickers out there suffer the same problem. A Javascript Date object "backs" them. And even if your date comes down the pipe as UTC, the Javascript date is "Regional", based on the Browser in which the site is loaded.

The fact is, a Date of Birth does not care about Timezones. It is constant. So it is pretty offensive when a user selects a Date of Birth and the previous day is what is actually sent to the server. I almost threw the baby and the bathwater out and went with strings in a text input. That is bullet proof.

I digress. One solution that I have seen in several places (which didn't work reliably for us anyway) is code like this

persons[i].BirthDate = persons[i].BirthDate.replace(/\d+/,
        function (n) { return parseInt(n) + new Date().getTimezoneOffset() * 60000; }

I'm curious. Why 60000?

I've also seen this:

//Deal with dates in milliseconds for most accuracy
utc = d.getTime() + (d.getTimezoneOffset() * 60000);
newDateWithOffset = new Date(utc + (3600000*offset));

where offset is something like '+10'. What is the 3600000?

I would like to know what these things do before I put them in production. And perhaps the reason they did not work for us is because we did not understand them properly and did not compensate accordingly in other places e.g. the server.

Thanks.

onefootswill
  • 3,707
  • 6
  • 47
  • 101
  • Possible duplicate of [How do you create a JavaScript Date object with a set timezone without using a string representation](http://stackoverflow.com/questions/439630/how-do-you-create-a-javascript-date-object-with-a-set-timezone-without-using-a-s) – devlin carnate Jan 19 '17 at 21:55

1 Answers1

1

getTime delivers the time in milliseconds and getTimezoneOffset delivers it in minutes. Therefore one minute are 60 seconds or 60.000 ms.
3.600.000 ms = 3.600 s = 60 min = 1 h So the offest is measured in hours.

Sascha
  • 4,576
  • 3
  • 13
  • 34
  • Thanks. In the first code snippet, what is the point of adding the number of minutes to the parsed date? Is that to take it back to UTC? Or is it to take it from UTC to the regional time? I guess I'm confused about what it is converting from and to. – onefootswill Jan 19 '17 at 22:05
  • The getTimezoneOffset() method returns the time difference between UTC time and local time, in minutes.
    For example, If your time zone is GMT+2, -120 will be returned. So this function will bring you to UTC.
    – Sascha Jan 19 '17 at 22:13
  • the dodgy aspect to all this is that the GMT offset is different to the UTC offset for my city. So, that function does not work and returns me to 1 hour past UTC. Dates are not easy. – onefootswill Jan 19 '17 at 22:34