Reputation: 438
I have a dropdown list of timezones based of of .NET method System.TimeZoneInfo.GetSystemTimeZones
provided from my MVC controller. What I would like to do is capture the user's timezone (client side) and default the dropdown list to their timezone.
On both Chrome and Firefox when I type in new Date()
to the console I can get a string like Fri Jan 24 2020 08:50:02 GMT-0500 (Eastern Standard Time)
Other than parsing between the parentheses, is there a way to get the timezone string Eastern Standard Time?
Upvotes: 1
Views: 2283
Reputation: 6488
You can get the current timezone offset in minutes from the dates getTimezoneOffset
function. Then you can divide the number by 60
to get the actual offset in hours. Note that the offset is the additatively inverted number of the "GMT+0100" string.
const offset = new Date().getTimezoneOffset() / 60;
console.log('Offset: ', offset);
console.log('UTC: ', new Date().toUTCString());
console.log('GMT: ', new Date().toString());
See the docs:
The getTimezoneOffset() method returns the time zone difference, in minutes, from current locale (host system settings) to UTC.
Upvotes: 1
Reputation: 5181
I can suggest to use Moment
, which is a third party library for handling everything from time to dates. I really really recommend this.
Official Moment documentation: https://momentjs.com/
In your question you can get the time zone really easy using moment like:
var jun = moment("2014-06-01T12:00:00Z");
var dec = moment("2014-12-01T12:00:00Z");
jun.tz('America/Los_Angeles').format('z'); // PDT
dec.tz('America/Los_Angeles').format('z'); // PST
jun.tz('America/New_York').format('z'); // EDT
dec.tz('America/New_York').format('z'); // EST
// This gets you your current timezone
moment().tz(Intl.DateTimeFormat().resolvedOptions().timeZone).format('z')
// Other examples
jun.tz('Asia/Tokyo').format('ha z'); // 9pm JST
dec.tz('Asia/Tokyo').format('ha z'); // 9pm JST
jun.tz('Australia/Sydney').format('ha z'); // 10pm EST
dec.tz('Australia/Sydney').format('ha z'); // 11pm EST
Upvotes: 1
Reputation: 374
I used this to get the gmt text. It is rought, but might work
new Date().toString().split('(')[1].split(')')[0]
Upvotes: 6
Reputation: 748
How about this?
Intl.DateTimeFormat().resolvedOptions().timeZone
Upvotes: 3