Saturday, June 1, 2019 05:30 Th..." /> Saturday, June 1, 2019 05:30 Th..." /> Saturday, June 1, 2019 05:30 Th..."/>

I want to convert timezone into local time in javascript. ex: I have timezone: 10800 "timezone": 10800 To ====> Saturday, June 1, 2019 05:30

Thank you

1 Answers

1
nanabyte On Best Solutions

Calculate the current time in UTC:

const now = new Date(); // Note: this is local time
const nowUtc = new Date(now.getTime() + now.getTimezoneOffset() * 60000);
  • now.getTimezoneOffset() returns the time zone difference, in minutes, from current locale (host system settings) to UTC. We need this value to be milliseconds which is why we multiply by 60000

Calculate the 10800 offset in milliseconds:

const offsetInSeconds = 10800;
const offsetInMilliseonds = offsetInSeconds * 1000;

Calculate the date in the 10800 timezone:

const date = new Date(nowUtc.getTime() + offsetInMilliseonds);
  • We use offsetInMilliseconds as the new Date(value) constructor requires the time in milliseconds

Format the date:

const formattedDate = date.toLocaleString('en-us', { weekday: 'long', month: 'long', day: 'numeric', year: 'numeric', hour: 'numeric', minute: 'numeric' });
console.log(formattedDate);

Output:

Sunday, June 2, 2019, 6:00 AM