Discovering the Time Zone of any Nation with Vanilla JavaScript

Can someone please guide me on how to retrieve and display the Date, Time, Month, Year, Day, Hours, and Minutes of any country using Vanilla JavaScript? I have the country's name, country code (e.g. 'IN' for India), and Timezone Number (e.g. 19800 for Delhi) obtained from OpenWeatherAPI. Any assistance on achieving this would be greatly appreciated.

Answer №2

To determine the current time for a specific UTC offset, one can add it to the current UTC time using the Date constructor along with various getUTC..() functions to extract the time components.

It is important to note that fixed UTC offsets should be used with caution, especially for places like New York where the UTC offset may change due to Daylight Saving Time. Therefore, the correct UTC offset must be applied according to the specific moment in time.

When retrieving time information from an API with a UTC Offset (or Timezone Number), assuming that the UTC offset remains constant for a location would not be advisable.

function getTimeComponentsFromUTCOffset(timeMillis, utcOffsetSeconds) {
    const d = new Date(timeMillis + utcOffsetSeconds * 1000);
    return { 
      year: d.getUTCFullYear(),
      month: d.getUTCMonth() + 1,
      day: d.getUTCDate(),
      hour: d.getUTCHours(),
      minute: d.getUTCMinutes(),
      second: d.getUTCSeconds() 
    };
}

// NB: timeZoneNumber or UTC offset will vary according to local DST rules...
const inputs = [
    { timeZoneNumber: +28800, location: 'Perth' },
    { timeZoneNumber: +19800, location: 'Delhi' },
    { timeZoneNumber: +3600, location: 'London' },
    { timeZoneNumber: -14400, location: 'New York' },
]

console.log('Location'.padEnd(12), 'Year  ', 'Month ', 'Day   ', 'Hour  ', 'Minute', 'Second');
for(let input of inputs) {
    let time = getTimeComponentsFromUTCOffset(Date.now(), input.timeZoneNumber);
    console.log(input.location.padEnd(12), ...Object.values(time).map(s => (s + '').padStart(2, '0').padEnd(6)));
}
.as-console-wrapper { max-height: 100% !important; }

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

In Certain Instances, Javascript Popups Are Losing Focus

I've been completely puzzled by this issue. Here is a working example of the code: <a href="javascript:void(0);" onclick="openPopUp('Edit_Screen.aspx?Image_Id='+ '<%# Eval("Image_Id") %>','Popup',850,800);"> ...

Losing a specific characteristic of data occurs when assigning a JavaScript object

After dedicating a full day to investigating this case, I found myself losing hope. const Tests = (state = INIT_STATE, action) => { switch (action.type) { case GET_TEST_DETAIL: return { ...state, test: {}, error ...

Shader error in Three.js occurring on various computers with the same browser

For the last 3 months, I have been immersed in developing with Three.js, successfully using it across various browsers and computers. However, a week ago, an error started popping up on my home computer whenever I attempted to load my website: three.js:29 ...

What could be the reason my div is not displaying correctly?

I am currently developing a game using HTML, CSS, and jQuery. The game will involve falling blocks that the player needs to avoid. However, I am facing an issue with my jQuery implementation. When selecting a theme (only the dark theme is currently functi ...

What's the issue with the Global Var in JavaScript (JQuery)?

Why is this code not functioning as expected? I believed that by setting the "prw" and "prh" variables outside of the function where they are calculated, but within the scoping function, it would work. However, it's not! What am I doing incorrectly? ...

Placing a notification on duplicated JavaScript code

In the past, I've had the displeasure of seeing my sites completely ripped off (front end), with some individuals even going so far as to copy every piece of content, including the GA tracking code :) I'm considering inserting a hidden notice wi ...

Angular deep nested router interface

How can I set up nested views in Angular for the following routes? /#/app/dashboard /#/app/product/ /#/app/product/new Here is my current route configuration: $stateProvider .state('app',{ url: '/app', templateUrl ...

The React axios request triggers the UseEffect cleanup function to terminate all subscriptions and asynchronous tasks

I'm currently retrieving data from my API using axios, but the requests are not inside a useEffect function. In fact, I haven't used useEffect at all. Here's a snippet of my code: JSX: <form onSubmit={onSubmitLogin}> <div c ...

Moving back and forth within a range

One simple yet commonly encountered task involves looping through a range forwards and backwards: var currentIndex = 0; var range = ['a', 'b', 'c', 'd', 'e', 'f']; function getNextItem(directi ...

Is there a way to utilize a single function on two separate div elements?

Looking for a way to optimize my code that contains the addRow() and deleteRow() functions. Currently, I have duplicated these functions for both radio buttons and checkboxes. Is there a more efficient way to achieve this? function addRow(tableID) { ...

Tips for Creating a Smooth Slide-Down Effect in Your Navbar Menu

Desired Outcome - My aim was to create a smooth slide down effect for the navbar after scrolling. While I managed to achieve this, I am encountering an issue. The Issue - Whenever I scroll back up to the top, the navbar becomes sticky without any transiti ...

What is the best way to implement a sub-menu using jQuery?

After successfully implementing a hover effect on my menu item using CSS, I am now struggling to make the sub-menu appear below the menu item upon hovering. Despite my efforts to search for jQuery solutions online, I have not been successful. Are there a ...

How can JavaScript dynamically assign onclick functions with dynamic parameters?

Here's a piece of code I am working with: document.getElementById('img'+i).onclick = function(){popup_show('popup',array_msg[i]+'|||'+date('Y-m-d',strtotime(lec_date))+'-==-'+str_view_forConflict, &ap ...

How can I efficiently remove elements from the end of an array in Vue.js?

Is there a way to splice data starting from the back with a higher index? When clicking on the .delete div, how can I make it so the .image-box div deletes starting from the end? I need help implementing this feature in my code. Here is a snippet: < ...

Converting an array of objects in JavaScript to a categorized array based on dates

I have an array of objects containing dates and I need to categorize them based on specific date categories. const orders = [ { "order_id": "1", "description": "Description 1", "date": "2024-02-03T19:00:57.744Z", }, { "order_id": "2", ...

HTML does not contain React code within its structure

Check out this code snippet: <div id="myDiv"></div> When I try to render an h1 element with React into the div with id myDiv, it doesn't work as expected. Initially, I suspected that there might be some dependency issues in my project ca ...

Unlock the full potential of your database with ExpressJs and MySQL. Discover a superior option to Knex Interceptor for securing your data with

I have a dilemma with managing sensitive data in my MySQL tables. I need to encrypt these fields before insertion and decrypt them when retrieving the data. Here are three different approaches that I have considered: One option is to implement a DATABAS ...

The characteristics of angular js Service/Factory and how they influence functionality

I'm seeking clarification on the behavior of AngularJS, especially in terms of JavaScript. In my code, I have a controller that has an Angular factory injected into it. Here's a snippet from the controller: $scope.localObjCollection = myObjFac ...

Converting a JSON object into a different format using TypeScript

Looking for advice on how to efficiently convert JSON data into a specific format without hardcoding any values like "root" or "Amount". I want to create a reusable function that can be used in various scenarios. Currently, I am working with TypeScript and ...

What is the best way to store user inputs in a text file using ReactJS?

I have a contact form with three input fields and I would like to save the input values into a text file when users click on a button. How can I achieve this? Can you provide an example? Here is my code: import React, { } from 'react'; import l ...