4

I want to change JavaScript Object Time zone. I am able to access time of the required timezone but date objects still shows my local timezone with it.

new Date()
output //Thu Nov 18 2021 16:30:23 GMT+0500 (Pakistan Standard Time)

new Date().toLocaleString("en-US", {timeZone: "America/Los_Angeles"})
output //'11/18/2021, 3:30:40 AM'

 new Date().toLocaleString("en-US", {timeZone: "America/Los_Angeles", timeZoneName: "short"})
output //'11/18/2021, 3:30:54 AM PST'

new Date(new Date().toLocaleString("en-US", {timeZone: "America/Los_Angeles", timeZoneName: "short"}))
output //Thu Nov 18 2021 16:37:35 GMT+0500 (Pakistan Standard Time)

enter image description here

Álvaro González
  • 142,137
  • 41
  • 261
  • 360
  • 2
    A date object doesn't hold a time zone information. Some of its method format *to the local time zone* but the `Date` itself just holds the time as UTC. Can you explain what exactly you're trying to do? Do you want to display the time *for a different time zone*? Or adjust the date to a different time? Or something different? – VLAZ Nov 18 '21 at 11:46

1 Answers1

1

The JavaScript Date object doesn't support setting timezone, the best you can do is to format dates and times using Date.toLocaleString() as in your code.

Dedicated date/time libraries such as luxon do support setting the timezones for DateTime objects very simply.

I would suggest using one of these libraries to get dates in another timezone, a simple example is shown below (getting datetime in LA timezone):

const { DateTime } = luxon;

const localTime = DateTime.now();
const laTime = localTime.setZone("America/Los_Angeles")

console.log("Local Time:", localTime.toFormat('yyyy-MM-dd HH:mm'));
console.log("Los Angeles Time:", laTime.toFormat('yyyy-MM-dd HH:mm'));

console.log("Local Time (hour, minute):", localTime.hour, localTime.minute);
console.log("Los Angeles Time (hour, minute):", laTime.hour, laTime.minute);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdn.jsdelivr.net/npm/luxon@2.1.1/build/global/luxon.min.js"></script>

You can try to do something like below using the native Date object, however, it's a hack really and will not always give accurate results:

function getDateInTimezone(date, timeZone) {
    // Using a locale of 'sv' formats as an ISO date, e.g. yyyy-MM-dd HH:mm.
    const timeInTimeZone = date.toLocaleString('sv', { timeZone } );
    // Pass this to the Date constructor
    return new Date(timeInTimeZone);
}

const localTime = new Date();
const timeZoneList = ['Asia/Karachi', 'Europe/Paris','America/Los_Angeles'];

console.log(`Local Time: ${localTime.toLocaleTimeString()}`);
for(let timeZone of timeZoneList) {
    const dt = getDateInTimezone(localTime, timeZone);
    console.log(`Time (${timeZone}): ${dt.toLocaleTimeString()}`);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40