Search code examples
javascripttimezonejsfiddledst

JSFiddle reports different time than browser


When I run var d = new Date; alert(d.toLocaleString()) in jsFiddle, or in the w3Schools "Tryit Editor", it is able to detect the location that I have set my computer to and report the correct time for that location (or at least, the one I had chosen at page load), taking into account its time zone and whether it uses Daylight Saving Time. The getTimezoneOffset() method also reports the correct offset for my chosen location. However, when I use this javascript in my webpage and leave the browser to interpret it, I get different behaviors by browser:

  • In Chrome, it always alerts the time in my real-life location, rather than the one I've chosen in the OS.
  • In Firefox, it fails to take DST into account in any location besides my real-life one, and reports the time one hour before my system time.
  • In Safari, it works like jsfiddle.

Can anyone explain these discrepancies, and suggest how I can get my website to behave like jsfiddle does?

edit: http://jsfiddle.net/5p8tL/, versus:

<html>
<body>
<script>
     var d = new Date;
     alert(d.toLocaleString());
</script>
</body>
</html>

Solution

  • The discrepancies you're seeing are likely due to the way that each browser reads the time zone settings from the system.

    • Chrome only reads the time zone when it is first started. If you change the system time zone, it won't pick up on those changes until it is restarted.

    • Internet Explorer on Windows will read the time zone on startup, and also listens for messages from the OS that alert it to the time zone changing. I don't have access to a Mac at the moment, but I assume that Safari on OSX does something similar.

    • Firefox is buggy in this regard. It appears to read the time zone settings at some interval, because if you change them and check without restarting, it doesn't see it right away. But then eventually it does. Also, there seem to be differences in how the time zone is applied between toLocaleString and toString when it's in this limbo state. If you wait awhile, then eventually it all syncs up. There are some other known issues with Firefox reporting time zones incorrectly, as I describe as part of this blog post. However this is the first time I've heard of it not applying DST properly on the clock itself, and I cannot reproduce that on Windows so it may be an Firefox-OSX specific bug. It wouldn't surprise me.

    At any rate, it's probably a good idea to fully restart the browser after changing time zone.

    As to why you don't see the same behavior in jsFiddle as you do on your own web page - I have no idea. In principal, that doesn't make any sense. They should have identical behaviors. Perhaps those instances were being restarted while the others were not? Just guessing.

    Also, you should probably use new Date() instead of new Date. It's valid, but JSLint will complain. See also this post.