Reputation: 232
I am having the time zone offset using the below code. I want to find out the list of timezone names associated with the timezone offset.
new Date().getTimezoneOffset().toString()
Upvotes: 2
Views: 5071
Reputation: 2255
You can do it in two steps in vanilla js using intl
object, local "ia" (see https://stackoverflow.com/a/64262840/1061871) and Intl.supportedValuesOf('timeZone')
(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/supportedValuesOf):
const getOffset = (tz) => Intl.DateTimeFormat("ia", {
timeZoneName: "shortOffset",
timeZone: tz
})
.formatToParts()
.find((i) => i.type === "timeZoneName").value // => "GMT+/-OFFSET in hh:mm"
.slice(3); //remove the GMT to get the offset in hh:mm
const getTZList = (offset) =>
Intl.supportedValuesOf('timeZone').filter(tz => getOffset(tz) === offset)
console.log(getTZList("-3:30"), getTZList("")) //for list of timezone in gmt/utc use empty string, not 0
edit, forgot : date object to offset in +/-hh:mm format
const getUtcOffset = (dateObject = new Date()) => {
const offset = dateObject.getTimezoneOffset(), o = Math.abs(offset);
return (offset === 0 ? '' : ((offset < 0 ? "+" : "-") + ("00" + Math.floor(o / 60)).slice(-2) + ":" + ("00" + (o % 60)).slice(-2)));
}
console.log(getTZList(getUtcOffset(new Date()))
Upvotes: 1
Reputation: 13369
I think the you have to use moment-timezone.js
library for this.
(Link here: https://momentjs.com/timezone/)
The approach should go along this lines:
moment.tz.names()
function to get all the available timezone locations.moment.tz.zone(name)
function to get the zone objectoffsets
property from the zone object to get the location offsetThe code will look something like this:
const tzNames = moment.tz.names();
const map = new Map();
for (const name of tzNames) {
const offsets = moment.tz.zone(name).offsets;
for (const offset of offsets) {
if (!map.has(offset)) {
map.set(offset, new Set());
}
map.get(offset).add(name);
}
}
const currentOffset = new Date().getTimezoneOffset();
const offsetList = map.get(currentOffset);
console.log('currentOffset: ' + currentOffset);
console.log('offset list size: ' + offsetList.size);
console.log('Total different offsets: ' + map.size);
console.log('List items: ');
for (const item of offsetList) {
console.log(item);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
Upvotes: 2