How to get the current time zone in best way – JavaScript

We have learnt on how to read different times from various time zones. Let us do the other way round here. Suppose you need to know your present location and that too without using any date function. The Intl.supportedValuesOd('timeZone') method that we have used in previous tutorials, returns the list of all available time zones and that support our environment. This is a huge list and its often hard to pin point your current time zone from these.

So, we may use other JavaScript supported functions that return a user’s active and current time zone. Let us check its syntax and how it works.

DateTimeFormat Prototype

You can use the Intl.DateTimeFormat.prototype.resolvedOptions() method which returns a new object along with properties that reflect the locale, date and time formatting options that are computed during initialization of this Intl.DateTimeFormat object. You may use it as follows.

const current_timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
		console.log(current_timezone); // example Asia/Dubai

timeZone

You can pass a value for the property in the options argument. When left undefined, it represents the runtime’s default time zone, this is when no option is provided.

The method is useful to get the current time zone. You may also pass it an option for the locale, as shown below.

const region1 = new Intl.DateTimeFormat('en-US', { timeZone: 'UTC' });
const options1 = region1.resolvedOptions();

The code above takes in custom options from the user. This works well to show time zones of different locations.