Get timezone difference between client and server

Do you need to know the timezone of the location or the machine?

If you need to know the timezone of the location then your best bet is to subscribe to a Geo-IP service, and check the IP, then checking on the timezone for that location (there are publicly available databases for that). It's not guaranteed as IP geographic information is not guaranteed (and that's definitely not just a theoretical lack of guarantee, mis-information abounds).

Often though, what you really want is the client machine's timezone setting. For most services I would find it annoying if I was travelling and had a website think of me to be in a different time to that I was working in (I stick to my home timezone if I'm not out of it for long).

This is easily done client side. new Date().getTimezoneOffset() returns the number of minutes between UTC and local time. E.g. currently I'm in Irish Summer Time (GMT + 1hour daylight saving time), and it returns -60.

You can easily put that in a URI used by an image or XHR request, or put it in a cookie value.


You could:

1 - Return the server date to the client as a Javascript date variable.
2 - Create a new javascript date client side (var currentTime = new Date();) and subtract the above date
3 - Post the result back to the server (if necessary; you may only need to know the difference client-side).

Update

Here is an example:

serverDate = new Date('<%= DateTime.Now.ToString() %>'); 
clientDate = new Date(); 
diffMin = (serverDate.getTime()-clientDate.getTime())/(1000*60);
alert("serverDate: " + serverDate + "\r\n" + "clientDate: " + clientDate + "\r\n" +
  "diffMin: " + diffMin);

If the server and client are on the same machine, you will see a diffMin approaching zero. There is a slight difference between the dates due to the time between the server-side script generating the date and the browser parsing and executing the javascript.

//This was useful for me - DateTime.Now.ToString("yyyy-MM-ddTHH:mm:ss")