DEV Community

Cover image for Dynamically change timestamp based on time zone in JavaScript
Hardique Dasore
Hardique Dasore

Posted on • Updated on

Dynamically change timestamp based on time zone in JavaScript

In order to dynamically change timestamp based on time zone in JavaScript you first need to get your system’s IANA time zone in JavaScript using:

console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)
Enter fullscreen mode Exit fullscreen mode

Once you have your system’s time zone, you need to assign the value of timestamp to a variable. The time stamp can be of any format, the following code is using ISO date format which is commonly used by Azure B2C, etc. In the next step we need to convert the date to a string using toLocaleString() method which helps in the sensitive representation of the date. You can now use the string to change the time stamp to your time zone.

var timeStamp = new Date("2011-08-12T20:17:46.384Z"); 
//ISO date format
console.log(timeStamp.toLocaleString('en-US', { 
   timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone 
}))
Enter fullscreen mode Exit fullscreen mode

Use case: If you have a global web application and you want to display time stamp of account creation to the application administrator.

Image description

Follow us on Instagram

Top comments (1)