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; }