0

I am using JavaScript API (new Date()).toString() to detect time zone for client? However, I found different Windows client will return different time zone name for the same time zone. For Example, we can get a time zone name as below if the client is in the GMT+0100.

Mon Sep 25 2017 21:04:22 GMT+0100 (GMT Summer Time)

Mon Sep 25 2017 21:04:22 GMT+0100 (GMT Daylight Time)

One name contains Summer and another name contains Daylight. How can make this API return the same time zone name like GMT Daylight Time?

shengt
  • 21
  • 1
  • 2
    Javascripts Date API sucks and you'll throw yourself off a building from frustration. Here use [moment.js](https://momentjs.com) and their awesome [timezone](https://momentjs.com/timezone/) library. It will spare the concrete. – Darkrum Sep 27 '17 at 01:38
  • @Darkrum Thanks for your information. We are using [jsTimezoneDetect](https://bitbucket.org/pellepim/jstimezonedetect) to detect it now, however, it will detect wrong time zone for some Daylight or non-Engilsh OS clinet. Do you think it will support this scenario? – shengt Sep 30 '17 at 02:20

1 Answers1

1

How can make this API return the same time zone name like GMT Daylight Time?

You can't. The ToString function of the Date object returns an implentation specific value. Ideally, it would show a human readable name of the time zone in the current locale, but in practice it can be just about anything, and there is no consistency across implementations.

Besides, neither name is correct. The only correct English name for for daylight saving time in the United Kingdom is "British Summer Time".

HOWEVER, if you are targeting only newer environments that fully support the ECMA Internationalization API (ECMA-402), then you can use the ToLocaleString function, like so:

new Date().toLocaleString('en-GB', { timeZone: 'Europe/London', timeZoneName: 'long' })
//=> "27/09/2017, 06:00:20 British Summer Time"

The result should be consistent, when it is available. Just keep in mind that this is a relatively new API and it isn't implemented in older browsers.

Matt Johnson-Pint
  • 197,368
  • 66
  • 382
  • 508
  • Thanks Matt. We want to find a way to detect current user's client time zone. The API you provided can be used for the scenario that the time zone is known. Do you know some other way we can use to detect the time zone? – shengt Sep 30 '17 at 02:31
  • Yes, that has been asked and answered a few times. [Here is one such place](https://stackoverflow.com/a/18252251/634824). BTW, try avoiding [XY Problems](https://meta.stackexchange.com/a/66378/201534) in the future. :) – Matt Johnson-Pint Sep 30 '17 at 23:01