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

Understanding the meaning of `.then()` in Excel JavaScript involves recognizing its function

Excel.run(function (context) { var sheet = context.workbook.worksheets.getItem("Sample"); var range = sheet.getRange("B2:C5"); range.load("address"); return context.sync() .then(function () { ...

A guide on arranging the JSON array within an AngularJS controller

Can someone assist me with sorting the JSON list provided below in the controller and then displaying it in the view? The orderBy filter only sorts one level, but I need it to sort recursively for all children. Input: R2 -->S4 ------>T5 ------> ...

Anticipate receiving a 'Type' returned by external library functions

I've recently started learning TypeScript and have encountered a situation where I need to assign a type to a variable that is returned from a third-party library function with its own type definition. For instance: import {omit} from 'lodash&ap ...

Animations are failing to run within a Bootstrap card when using Vue rendering

I have utilized Bootstrap cards to display pricing information in my project. I implemented a collapse feature for half of the card when the screen size is equal to mobile width. While using vanilla Bootstrap, the animation worked seamlessly with the col ...

Git only keeps track of the changes made to files, not the

I am facing an issue with my npm project. Whenever I run npm start A bundle of files is created, named like *-bundle.gz If I make minor changes to files like font.php, and then run npm start again, new files named *font-bundle.gz are generated with a n ...

Alerting JavaScript with element Selector doesn't function at full capacity

I am currently implementing Notify JS from the following source : Below is the HTML code I am using: <div> <p><span class="elem-demo">aaaa</span></p> <script> $(".elem-demo").notify( "Hello Box" ...

Items seem to vanish into thin air and become immovable when attempting to relocate them

I am attempting to create a unique grid layout with 3x3 dimensions, where each grid item represents a fragment of a single image. These items should have the capability to be dragged and dropped inside another 3x3 grid, in any desired sequence. I have hit ...

Manage and display data in Vue.js using the CLI

I'm currently developing a form where users can input data and I need to display that data on another page using Vue.js Below is the form I have created: <form id="main-contact-form" class="contact-form r ...

Querying Techniques: Adding an Element After Another

CSS <div id="x"> <div id="y"></div> <div> <p>Insert me after #y</p> The task at hand is to place the p tag after '#y', and whenever this insertion occurs again, simply update the existing p tag instead of ...

Is it possible to incorporate a combination of es5 and es2015 features in an AngularJS application?

In my workplace, we have a large AngularJS application written in ES5 that is scheduled for migration soon. Rather than jumping straight to a new JS framework like Angular 2+ or React, I am considering taking the first step by migrating the current app to ...

Give a jQuery Mobile flipswitch a new look

Currently, I am using jQuery Mobile and recently attempted to refresh a flipswitch. However, upon executing the code $("#flipEnabled").slider("refresh");, I encountered an error in the console: Uncaught Error: cannot call methods on slider prior to initial ...

What is the best way to showcase information within a node framework?

I am looking to create a family tree using the MVC framework. Furthermore, I need to be able to insert data with relationships. I have object data that I would like to display along with its entities in a node structure. Any assistance on this matter wou ...

What causes React Native linking to result in a workspace integrity issue?

Struggling with developing a React Native app, I faced challenges. After creating both a native module and a native UI component, my goal was to publish them as an NPM module. However, when attempting to integrate these into a new React Native app using ...

Tell me about node-persist

During my online learning journey of Node.js on Udemy, I encountered the term node-persist. Despite searching for it on Google, I couldn't find a clear explanation. Could someone please provide a concise definition of what node-persist is? ...

Using JQuery to pass a concatenated variable

What is the reason behind the success of this code: $(".ab").css({'background':'#ce0000','color':'#EEE'}); While this code does not work: f("ab"); function f(ab){ var x = '".'+ ab +'"'; ...

Transform the appearance of a button when focused by utilizing CSS exclusively or altering it dynamically

As a newcomer to coding, I am currently working on a project that involves changing the color of buttons when they are clicked. Specifically, I want it so that when one button is clicked, its color changes, and when another button next to it is clicked, th ...

Discovering the quantity of identical elements within a JavaScript array

Looking for some assistance in solving a JavaScript problem as I am relatively new to the language: I have an array and I need help in determining the count of identical values. Below is my array: var arr = ["red", "blue", "green", "red", "red", "gray"] ...

Issues with click events in the navigation menu

How can I make my menu close when clicking on other parts of my website, instead of opening? I know that I should use a click event for this, but when I implemented a click event, my menu encountered 2 unwanted problems: 1- Whenever I clicked on a menu i ...

Initiate the React application with the given external parameters

I have created a React app that is embedded within a webpage and needs to start with specific parameters obtained from the page. Currently, I am passing these parameters in the index.HTML file within a div element. The issue arises when these parameters ar ...

Dynamically loading Ember templates with asynchronous requests

I need a way to dynamically load HTML content from another file using the code below: App.MainView = Ember.View.extend({ template:function(){ $.ajax({ url: 'views/main.html', dataType: 'text', async: false, ...