Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get UTC + 1 time with javascript

var options = { timeZone: 'UTC', timeZoneName: 'short'};
const today = new Date();
$w("#pikoTimer").text = today.toLocaleTimeString("en-GB", options);

This is my code i want to use, so when I click a button it sets the text to UTC time - with UTC it works fine but I want to set it to UTC + 1 and I cant find a solution.

When i try timeZone: 'UTC+1' it gives me an error saying: RangeError: Invalid time zone specified: UTC+1

like image 805
Dominik Lemberger Avatar asked Sep 15 '25 20:09

Dominik Lemberger


2 Answers

The ECMAScript Language Specification stipulates (ECMA-262 section 20.4.4.40) that the options parameter of the Date.prototype.toLocaleTimeString() function is to be implemented as specified in ECMA-402 (the ECMAScript Internationalization API Specification).

According to ECMA-402, the timeZone option is valid if it conforms to section 6.4 (“Time Zone Names”), which stipulates:

The ECMAScript […] Internationalization API Specification identifies time zones using the Zone and Link names of the IANA Time Zone Database. Their canonical form is the corresponding Zone name in the casing used in the IANA Time Zone Database.

Which is why your code works when using UTC (which is a link to Etc/UTC in the IANA Time Zone Database), but you get an error when using UTC+1 (which is not a valid IANA Time Zone).

Instead, you should use a value that represents the same UTC+01:00 offset, and observes desired daylight time adjustments. For example, you may use Europe/Paris or Europe/Belgrade.

const options = { timeZone: 'Europe/Paris', timeZoneName: 'short'};
const today = new Date();
$w("#pikoTimer").text = today.toLocaleTimeString("en-GB", options);

See List of tz database time zones for a handy online reference.

like image 195
Eric Redon Avatar answered Sep 18 '25 09:09

Eric Redon


you should specify time zone name in option's timeZone field like timeZone: 'Australia/Sydney' or timeZone: 'EST'; and utc+1 is a invalid time zone name. read more in mdn Intl/DateTimeFormat; you can use a city name with the time zone you want like this:

const options = { timeZone: 'Europe/London', timeZoneName: 'short'};
const today = new Date();
console.log(today.toLocaleTimeString("en-GB", options))
like image 34
Mhmdrz_A Avatar answered Sep 18 '25 10:09

Mhmdrz_A