I am using jsTimezoneDetect script to detect user current timezone. Code below display result as America/Chicago
. Is there a way to display CDT
/CST
(depending on today date)?
var timezone = jstz.determine();
timezone.name();
Or is there any other script I can use?
I am using jsTimezoneDetect script to detect user current timezone. Code below display result as America/Chicago
. Is there a way to display CDT
/CST
(depending on today date)?
var timezone = jstz.determine();
timezone.name();
Or is there any other script I can use?
Share Improve this question asked May 22, 2015 at 16:34 αƞjiβαƞjiβ 3,26615 gold badges63 silver badges104 bronze badges2 Answers
Reset to default 9First understand:
- A time zone abbreviation is potentially ambiguous (5 different CST's).
- Not all time zones have meaningful abbreviations. Some are just made up to plete the API, but not actually used by people in the region (MSK in Belarus).
- There are often disagreements about the correct abbreviation to use (HST vs HAST).
- They are usually in English, though other languages may have different abbreviations for the same time zone. (PST vs HNP (French))
- The abbreviation depends highly on the specific date chosen - as it could change for daylight saving time (EST vs EDT).
In many browsers, you can get the abbreviation directly (via ECMA-402) by:
const d = new Date(); // now, or the specific date in question
const tz = d.toLocaleString('en', {timeZoneName: 'short'}).split(' ').pop();
console.log(tz);
This doesn't necessarily work everywhere though.
Since you're working with jsTimeZoneDetect, you already have an IANA time zone identifier ("America/Chicago"). So, you could get it from moment-timezone, like this:
var m = moment(); // now, or the moment in question
var s = m.tz('America/Chicago').format('z');
That will work everywhere, but you have the overhead of moment and moment-timezone, and jstz, which is probably overkill unless you are using these libraries for other purposes anyway.
You might also consider a server-side solution. For example, if you're using PHP, you can use this code. Or, if you're using .NET, you can use my TimeZoneNames library.
In native JS you could:
var d = new Date();
timezone = d.getTimezoneOffset();
and then go over it with a switch.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744752861a4591703.html
评论列表(0条)