Reputation: 95
Been trying to wrap my head around this for a good time now, but I can't think of a good way to do it.
I have an array with a bunch of different UTC time zones (in just format -07, -01, +03, +10, etc). What I'm trying to achieve is a way to show the local time of those time zones, possibly including the day and month.
Here's an example of the resulting string: Local time: 14:09 23/08
Upvotes: 0
Views: 1274
Reputation:
You can use Date.prototype.getTimezoneOffset()
to get your local timezone. Calculate the difference between your local timezone and the destination timezone, multiply it with 3600000 and add it to a Date object containing the current time.
const now = new Date();
const timezoneOffset = now.getTimezoneOffset() / 60;
const timezones = ['-07', '-01', '+03', '+10'];
timezones.forEach(timezone => {
const difference = +timezone + timezoneOffset;
const time = new Date(now.getTime() + difference * 3600000);
console.log(`Local time: ${time.toLocaleTimeString([], { timeStyle: 'short', hour12: false })} ${time.toLocaleDateString([], { month: '2-digit', day: '2-digit' })}`);
});
Upvotes: 1