Is there a way to retrieve the timezone based on a province or state in TypeScript on the frontend?

I've been working on an angular app that allows users to select a country and state/province. My current challenge is determining the timezone based on the selected state/province, with a focus on Canada and the US for now (expanding to other countries later). The user's selection includes both the full name of the state/province and its two-letter abbreviation. I'm searching for an NPM package or JavaScript library that can take the province/state input and provide the corresponding timezone information.

One potential solution I came across is:

https://www.npmjs.com/package/city-timezones

However, this is a node package and I need something compatible with frontend typescript. Are there any alternatives available?

Answer №1

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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trigger ExtJS input file event when dialogue window is closed

How can we capture the event when a file is selected in an open dialogue box and the OK button is clicked in extjs? **Off topic, the field does not stretch from its normal width. xtype: 'textfield', fieldLabel: 'New (JPG or ...

Displaying AJAX response with AngularJS

My Angular script structure is shown below: var myapp = angular.module("Demo",["ngRoute"]) .config(function($routeProvider){ $routeProvider .when ...

Guide on setting up and configuring the seeder in MikroORM

Hey there, I recently tried to execute seeders in MikroORM and encountered a problem. I followed all the steps outlined here: . In the MikroORM route folder (alongside mikro-orm.config.ts), I created a seeders directory. I updated mikro-orm.ts with the fo ...

JavaScript Email Verification

I am designing my website and encountering an issue with the email checker. I can't figure out why it's not working, especially since I have never used JavaScript before. This is what I tried: var flag=true; var st = Form1["email"].value.ind ...

The dimensions of the box are not predetermined by the size of the photo

I'm attempting to develop a photo gallery that emulates the style of (using the Unsplash API -> ) However, the size of the container box does not adjust properly with the photos. <div className="imageGrid__container"> <di ...

Encountering a problem when trying to launch a Hyperledger business network

I successfully completed all the steps to configure the hyperledger business network by following the instructions provided in this link. Although I managed to configure all the steps, I encountered a roadblock at the final step of starting my business ne ...

Send only the modified form fields when making an AJAX PUT request to the REST API

I need to update my data using an AJAX request triggered by clicking the Save button on a form with multiple fields. Currently, the update only works when all fields are filled out because I'm passing $('#field').val(). But what if I only wa ...

Unleash the power of jQuery by incorporating the Ajax functionality with a hover option to enhance user interactivity. Utilize the .ajax

On my website, I have a calendar displayed with dates like "11/29/2014" stored in an attribute called "data-date". The goal is to check the server for a log file corresponding to that date and change the CSS of the div on mouse hover. Here is the current ...

The autocomplete feature fails to properly highlight the selected value from the dropdown menu and ends up selecting duplicate values

After working on creating a multiple select search dropdown using MUI, my API data was successfully transformed into the desired format named transformedSubLocationData. https://i.stack.imgur.com/ZrbQq.png 0: {label: 'Dialed Number 1', value: &a ...

Filtering JSON Objects in JavaScript: A Comprehensive Guide

I have been attempting to filter the JSON object below and create an array of objects that have a value containing "steve" in the key 'markdown'. My initial approach involves converting the object to an array then applying a filter. Although I h ...

The specified type '{ songs: any; }' cannot be assigned to the type 'IntrinsicAttributes' in NEXTJS/Typescript

I am currently working on a straightforward script. Below is the index.tsx file for my Next.js application: import type { NextPage } from 'next' import SongsList from '../components/SongsList/SongsList' import { GetStaticProps } from & ...

Ways to "Compile out" log commands

In my typescript project, there is a section of code dedicated to creating debug information. However, upon profiling the application, I discovered that this debug code is causing a significant performance impact. Currently, my approach involves setting a ...

Trouble loading Styled Components in React Typescript with Webpack configuration

Hey there! I'm diving into the world of styled components for the first time, and I'm a bit lost on where I might have slipped up. I've got my webpack all sorted out and my .babelrc file in place. As I was going through the Styled Component ...

Developing a custom directive that utilizes a dynamic ng-options configuration

Alright, let me share with you my personalized directive: angular.module('bulwarkWebControls', []) .directive('customDropdown', [ function() { return { scope: { label: '@', // can be om ...

Choose options with identical titles

If you click on the button to add more selects with the same name, I want to replace them so that you can access them in a PHP array. document.querySelector('#add').onclick = function () { var thespan = document.createElement('span&apos ...

Issue: No property named 'counterUp' has been defined on the 'JQLite' type

I’m attempting to implement the counterUp() function from JQuery into my Angular project, but I keep encountering an error. The error message mentions jqlite instead of jquery. I have attempted to rectify the issue but have not been able to find a su ...

I'm having trouble with my useState in React/NEXTjs because it's not adding onto the result of a socket.io event from the server, it's simply

Frameworks used: Next.js, Socket.io, React I am currently working on a straightforward messaging application. The main concept involves emitting a message typed by a user, sending that message to the server, and then broadcasting it back to all clients th ...

Is it possible to assign a variable to an Ionic datetime input property?

I am trying to pass a variable, someVar, into the max attribute (input property) of an Ionic 2 (and Angular 2) DateTime component. It seems like it only accepts a hardcoded string such as max="2017-08-31". HTML <ion-datetime displayFormat="DD/MM/YYYY" ...

What is the process for redirecting to an external URL while including post parameters?

When a user accesses my endpoint, I need it to automatically redirect them to an external URL with URL-encoded form parameters. Endpoint: https://example.com Form Parameters: Name: testing ID: 123456 I have attempted the following in Express. It succes ...

Ways to rearrange div elements using JavaScript

I need assistance with reordering div elements using JavaScript, as I am unsure of how to accomplish this task. Specifically, I have two divs implemented in HTML, and I would like the div with id="navigation" to appear after the div with class="row subhea ...