Search code examples
javascripttimezonelocaleutc

Does toLocaleString use the users timezone or the computer that hosts the code?


I need to convert a timestamp into human readable format. I'd like the resulting human readable format to be the users location (not the computer I deployed my code to).

I currently have this:

let d = 1662835646;
new Date(d * 1000).toLocaleString()

Which gives me this:

9/10/2022, 2:47:26 PM

Which is correct for my timezone (EST) but I don't have a way to test this for other timezones.

Basically all I'm asking is, will the above code work to where a user could be anywhere else in the world and it will show the correct date relevant to THEIR location.


Solution

  • Basically all I'm asking is, will the above code work to where a user could be anywhere else in the world and it will show the correct date relevant to THEIR location.

    Yes, by default, the default locale and time zone are that of where the code is executing - not where it is hosted. This is true at least for browser-based JavaScript, that means it will be that of the user. For server-based JavaScript (Node.js, etc.), it will be that of the server, because that's what's executing the code.

    ... I don't have a way to test this for other timezones.

    Yes you do. You can change your computer's time zone and locale (language) settings and restart your browser.

    Alternatively, if you're using a Chromium based browser like Google Chrome or Microsoft Edge, you can change the location in the Sensors area in the dev tools. Each location can be customized for locale and time zone.

    enter image description here