If you're looking to create a convenient lookup table for timezones based on country and province, consider using the city-timezones
library. Here's an example of how you can achieve this:
<script type="module>
import cityTimezones from 'https://cdn.skypack.dev/city-timezones';
function groupTimezones(country, arr) {
const countryData = arr.filter(city => city.country === country && city.timezone && city.province);
const sortedByProvince = countryData.sort((a,b) => a.province.localeCompare(b.province));
return sortedByProvince.reduce((acc, city) => {
const key = city.province;
acc[key] = acc[key] || [];
if (!acc[key].includes(city.timezone)) {
acc[key].push(city.timezone);
}
return acc;
}, {})
}
console.log('Canada:');
console.log(JSON.stringify(groupTimezones('Canada', cityTimezones.cityMapping), null, 4));
console.log('United States:');
console.log(JSON.stringify(groupTimezones('United States of America', cityTimezones.cityMapping), null, 4));
</script>
The above code snippet will generate a list of timezones for each province in Canada and the United States.
This information can be utilized in frontend applications where user input may not always be necessary if there is only one timezone per province.
In cases where provinces have multiple timezones, you can prompt users to select the appropriate one or display commonly used names like 'Central Time' or 'Eastern Time' instead of IANA zone names.
To find alternative timezone names, you can utilize tzdb
. Check out an example implementation below:
<script type="module>
import cityTimezones from 'https://cdn.skypack.dev/city-timezones';
import { getTimeZones, rawTimeZones, timeZonesNames } from 'https://cdn.skypack.dev/@vvo/tzdb';
const timeZones = getTimeZones();
function groupTimezones(country, arr) {
const countryData = arr.filter(city => city.country === country && city.timezone && city.province);
const sortedByProvince = countryData.sort((a,b) => a.province.localeCompare(b.province));
return sortedByProvince.reduce((acc, city) => {
// Get the alternative name, e.g. Eastern time
const altTz = (timeZones.find(t => t.name === city.timezone || t.group.includes(city.timezone)) || []).alternativeName || 'NotFound - ' + city.timezone;
const key = city.province;
acc[key] = acc[key] || [];
if (!acc[key].includes(altTz)) {
acc[key].push(altTz)
}
return acc;
}, {})
}
console.log(JSON.stringify(groupTimezones('Canada', cityTimezones.cityMapping), null, 4));
console.log(JSON.stringify(groupTimezones('United States of America', cityTimezones.cityMapping), null, 4));
</script>
Situations where certain provinces have multiple timezones can be handled by allowing users to choose among them. For instance, when selecting British Columbia, users could be asked to pick between Mountain Time, Pacific Time, or Yukon Time.