Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript on Mac (Safari) toLocaleTimeString() oddities

We have a simple function the works out a duration, it works fine in every browser apart from Safari on a Mac (works in chrome on the mac, works on Safari on the PC)

For example,

new Date().toLocaleTimeString() 

We expect this to give a time formatted like this:

11:59:25

However, on the Mac Safari we get this

11:59:25 GMT+01:00

Any calculations we do on these times are one hour out (its adding the hour onto the calculation)

e.g. 11:59:25 - 11:59:25 = 01:00:00 (should be 00:00:00)

Any ideas?

Why is it adding the time zone to the string? this caused us a little issue with our database

Why is it adding an hour to the sting?

Why just in that one bloody browser!

Thanks for your time.

like image 821
Keeno Avatar asked Mar 29 '11 11:03

Keeno


1 Answers

The toLocaleTimeString method relies on the underlying operating system in formatting dates. It converts the date to a string using the formatting convention of the operating system where the script is running. For example, in the United States, the month appears before the date (04/15/98), whereas in Germany the date appears before the month (15.04.98).

Methods such as getHours, getMinutes, and getSeconds give more consistent results than toLocaleTimeString. Use toLocaleTimeString when the intent is to display to the user a string formatted using the regional format chosen by the user. Be aware that this method, due to its nature, behaves differently depending on the operating system and on the user's settings.

Source: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Date/toLocaleTimeString

like image 56
Davorin Avatar answered Sep 28 '22 02:09

Davorin