Quantcast
Channel: Getting the client's time zone (and offset) in JavaScript - Stack Overflow
Viewing all articles
Browse latest Browse all 34

Answer by Dan Dascalescu for Getting the client's time zone (and offset) in JavaScript

$
0
0

A one-liner that gives both the offset and the time zone is to simply call toTimeString() on a new Date object. From MDN:

The toTimeString() method returns the time portion of a Date object in human readable form in American English.

The catch is that the timezone is not in the standard IANA format; it's somewhat more user-friendly, than the "continent/city" IANA format. Try it out:

console.log(new Date().toTimeString().slice(9));console.log(Intl.DateTimeFormat().resolvedOptions().timeZone);console.log(new Date().getTimezoneOffset() / -60);

In California right now, toTimeString() returns Pacific Daylight Time while the Intl API returns America/Los_Angeles. In Colombia, you'd get Colombia Standard Time, vs. America/Bogota.

Note that many other answers to this question attempt to obtain the same information by calling Date.toString(). That approach is not that reliable, as MDN explains:

Date instances refer to a specific point in time. Calling toString() will return the date formatted in a human readable form in American English. [...] Sometimes it is desirable to obtain a string of the time portion; such a thing can be accomplished with the toTimeString() method.

The toTimeString() method is especially useful because compliant engines implementing ECMA-262 may differ in the string obtained from toString() for Date objects, as the format is implementation-dependent; simple string slicing approaches may not produce consistent results across multiple engines.


Viewing all articles
Browse latest Browse all 34

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>