0

is it possible to convert a UTC date coming from a server to a specific (UK) timezone using JavaScript? This is for the case where users may have the incorrect local timezone configured.

isshesure
  • 213
  • 2
  • 10
  • Does this answer your question? [How to get the exact local time of client?](https://stackoverflow.com/questions/10659523/how-to-get-the-exact-local-time-of-client) – Anunay Sep 17 '20 at 16:12
  • No, this is converting to a fixed time zone, and how that works under the covers assuming the users browser/system settings are incorrect. – isshesure Sep 17 '20 at 16:49

1 Answers1

3

You can specify a time zone in the options passed to toLocaleString, which will use the point-in-time represented by the Date object to create a localized string that is converted to the specified time zone.

For example:

new Date("2020-09-17T17:15:00.000Z").toLocaleString('en-GB', { timeZone: 'Europe/London' })
//=> "17/09/2020, 18:15:00"

Note the first parameter is the locale for the format, not the time zone. If you don't want a specific format, you can pass undefined instead - which will use the user's active locale settings to choose the format.

Note also that you can not get a Date object that is in that time zone. The Date object only stores a point in time (as a Unix timestamp with millisecond precision), and it always uses the computer's local time zone setting for its functions that need local time conversions (except as show above).

(The TC39 Temporal proposal is working to improve this.)

Matt Johnson-Pint
  • 230,703
  • 74
  • 448
  • 575
  • thanks, how is the conversion to GMT or BST determined? – isshesure Sep 17 '20 at 17:48
  • 1
    The IANA time zone name `Europe/London` is an identifier for the UK time zone. Modern browsers (and Node.js) ship with this data, or use the underlying tzdata in the OS. That data has all the rules about whether GMT or BST are in effect and when. You can read more in [this timezone tag wiki](https://stackoverflow.com/tags/timezone/info), or [on Wikipedia](https://en.wikipedia.org/wiki/Tz_database). See [here](https://en.wikipedia.org/wiki/List_of_tz_database_time_zones) for a list of valid time zone names. – Matt Johnson-Pint Sep 17 '20 at 18:00