Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I want to Change Timezone of Date Object In JavaScript

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

like image 688
Muhammad Iftikhar Rasool Avatar asked Feb 01 '26 10:02

Muhammad Iftikhar Rasool


1 Answers

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/[email protected]/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; }
like image 155
Terry Lennox Avatar answered Feb 03 '26 22:02

Terry Lennox



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!