I have set a deadline in UTC, as shown below, and I'm wondering what exactly the toLocaleString() method will do to it on user's local machines. For instance, will it account for daylight savings if they are in a timezone that recognizes it? Or will I need to insert additional code that checks where the user is, and then fixes the displayed time?
var deadline = new Date('5/1/2013 ' + "16:15" + ' UTC'); alert(deadline.toLocaleString());
We don't know what exactly the
toLocaleString method does (§126.96.36.199):
This function returns a String value. The contents of the String are implementation-dependent, but are intended to represent the Date in the current time zone in a convenient, human-readable form that corresponds to the conventions of the host environment’s current locale.
But yes, most implementations will consider DST if it is active in the current local timezone. For your example I'm getting
"Mittwoch, 1. Mai 2013 18:15:00" - CEST.
Will I need to insert additional code that checks where the user is, and then fixes the displayed time?
I think you can trust
toLocaleString - the browser should respect the user's settings. If you want to do it manually, check out timezone.js.
As you use "UTC" the date itself will be UTC format, but the
toLocaleString() takes client's locale into account, which means it'll return the date in string updated with all and every changes typical to client's regional and locale settings (DST, date/time format, etc).
As JS documentation describes this: "The toLocaleString() method converts a Date object to a string, using locale settings.".
If you want to avoid this, use the
toUTCString() method instead.
Hope this helps!
If you want a consistent output, I would use a library to format your dates instead of relying on the default implementation. The best library (IMHO) for this is moment.js. The live examples on their main page will give you an idea of what it can do.
©2020 All rights reserved.