Retrieving time zone using offset with javascript

I am looking for a way to schedule time-based events on my server operating in UTC time.
For the user interface, I need to input 2 parameters:

  1. The local time when the scheduled event should trigger
  2. The timezone offset

Instead of displaying timezone names that can slow down page loading and are unnecessary, I prefer not to include them.

I have explored the moment library but couldn't find a direct method to retrieve the timezone name from the timezone offset. The API moment.tz.names() provides a list of all timezones.

Is there an API that could return something like

moment.tz.name('330') = 'Asia/Kolkata'
Additionally, if such a solution exists, would it also take care of any DST (Daylight Saving Time) related issues?

Answer №1

There are always multiple names associated with a particular offset, so there is no direct API function like

moment.tz.name('offset') = 'Country/Zone'
that exists.

However, you can retrieve an array of all names based on a given offset using a simple filter function:

const moment = require('moment-timezone');

const getZoneFromOffset = offsetValue => moment.tz.names().filter(zone => moment.tz(zone).format('Z') === offsetValue)

console.log(getZoneFromOffset("+05:30"))
// [ 'Asia/Calcutta', 'Asia/Colombo', 'Asia/Kolkata' ]

In the example above, I used "+05:30" as the offset value to demonstrate how to solve the problem. You can also gather an array of timezone names along with their offsets by applying a map function on moment.tz.names():

const getZoneObjects = () =>  moment.tz.names().map(zone => ({ zone, offset: moment.tz(zone).format('Z') }))

/*
[
  { zone: 'Africa/Abidjan', offset: '+00:00' },
  { zone: 'Africa/Accra', offset: '+00:00' },
  { zone: 'Africa/Addis_Ababa', offset: '+03:00' },
  ...
*/

The examples above utilize Z as the timezone format, but if "+5:30" doesn't fit your requirements, you can explore other formats listed at . For instance, ZZ would represent "+0530" in your scenario.

Answer №2

When dealing with fixed offsets, there is no need to utilize Moment-Timezone. Moment itself provides all the necessary functionality through either the parseZone or utcOffset functions.

You can find a relevant example in the official documentation.

...

An instance where this feature comes in handy is when you need to create a moment with a specific time zone offset using only numeric input values:

moment([2016, 0, 1, 0, 0, 0]).utcOffset(-5, true) // This is equivalent to "2016-01-01T00:00:00-05:00"

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

Merging arrays with the power of ES6 spread operator in Typescript

My goal is to merge two arrays into one using the spread object method as shown in the code snippet below: const queryVariable = { ...this.state, filters: [...Object.keys(extraFilters || {}), ...this.state.filters], } The this.state.filte ...

Managing state changes with a slider in ReactJS

I am currently working with the Foundation slider found at this link: click for doc. To access the slider's current value, they recommend using a hidden input like this: <div class="slider" data-slider data-initial-start="50" data-end="200"> & ...

How can we use fetch to grab some data?

I put together an Express application quickly, here's how it looks: const express = require("express"); const app = express(); const port = 3000; app.get("/content/1/", (req, res) => res.send("Thinking about taking out a new loan? Call us today. ...

Is it possible to modify the sub/child divs within a draggable parent div and assign them a different class?

Greetings, after being a long-time reader, I have finally decided to post for the first time. In the process of creating a webpage with jQuery drag and drop divs, I am curious about how to change the class of a child div within a draggable div once it is d ...

Conquering challenges arising from organizing subdirectories for js/css/xml files

During the process of developing a website with html, css, js and xml files stored on my computer (not yet online), I initially kept all the files in one folder along with an images folder. However, as the project progressed and things started to get mes ...

When provided with varied inputs, new Date() yields distinct values for various time zones

var date1 = "2015-03-29"; console.log(new Date(date1)); //Output:Sun Mar 29 2015 05:30:00 GMT+0530 (India Standard Time) var date2 = "1869-12-31"; console.log(new Date(date2)); //Output:Fri Dec 31 1869 05:53:20 GMT+0553 (India Standard ...

Deleting the first element of an array in JavaScript using Node.js

I'm struggling to remove the first element of an array. When I try to use slice(1,1) or shift, I can't seem to retain a list. For instance, my array: [1499783769720,"54:52:00:62:46:66","54:52:00:b0:fa:57","54:52:00:8f:d9:7c","54:52:00:e7:67:10" ...

Tips on customizing the MSAL login commands for successful integration with numerous users

Successfully implemented the code to login using a username and password combination with Cypress for a webapp integrated with MSAL. In the end-to-end Testfile: describe('Login with MSAL as xxUsername', () => { beforeEach(() => { cy.Lo ...

React.js encountered an error: Objects cannot be used as a React child (found: object containing keys {type, data})

My current project involves displaying MySQL data in a table using Node.js and React.js. However, I keep encountering the following error: Error: Objects are not valid as a React child (found: object with keys {type, data}). If you meant to render a colle ...

What's the best way to include various type dependencies in a TypeScript project?

Is there a more efficient way to add types for all dependencies in my project without having to do it manually for each one? Perhaps there is a tool or binary I can use to install all types at once based on the dependencies listed in package.json file. I ...

Utilize node.js to run a local .php file within a polling loop

Here is the purpose of my application in brief. I am using a PHP file to read data via an ODBC connection and then write that data to a local database. This PHP file needs to be executed LOCALLY ON THE SERVER every time a loop is processed in my node.js, ...

Conditional rendering with React.js in the DOM

Just starting out with React and encountering an issue with rendering using reactDom: index.js import ReactDOM from 'react-dom'; import A from 'components/A'; import B from 'components/B'; render(<A />, document.getEl ...

Modifying the user interface (UI) through the storage of data in a class variable has proven to be

If I need to update my UI, I can directly pass the data like this: Using HTML Template <li *ngFor="let post of posts; let i = index;"> {{i+1}}) {{post.name}} <button (click)="editCategory(post)" class="btn btn-danger btn-sm">Edit</butto ...

Substitute the attributes of one object with those of another

Alright, I'm revising this because it seems to be causing confusion. Imagine you have two items x and y. What I aim to do is swap all the characteristics of x with those of y. (Please note that this isn't your usual duplication process where a ...

Connect my asp.net grid view to JavaScript using AJAX

I am seeking guidance on how to bind my gridview from JavaScript in an ASP.NET web forms application. My objective is to click a linkbutton within my gridview and have it trigger a modalpopup that displays another gridview. Here are snippets of my code s ...

Using pdfkit to create a PDF and then returning it as a base64 string from a function

I am attempting to utilize PDFKit to produce a PDF file and then retrieve it as a base64 string. Here is the code snippet I am using: function generatePDFDocument(data){ let doc = new PDFDocument(); var bufferChunks = []; doc.on('readabl ...

Can anyone provide guidance on creating a Jest test for an authenticated Express endpoint?

I have been working on a seemingly straightforward 4-file toy solution that I thought was simple. I am looking to write a Jest test for the '/bingo' route in bingo.js which requires authentication. Below are the four files that make up this setup ...

What is the correct way to utilize preloads and window.api calls in Electron?

I am struggling with implementing a render.js file to handle "api" calls from the JavaScript of the rendered HTML page. The new BrowserWindow function in main.js includes: webPreferences: { nodeIntegration: false, // default value after Electr ...

Manifestation for JSON Firebug extension

In the process of developing a firebug extension, I encountered an issue with displaying JSON in the panel. Despite using a textarea to display the panel, the extension consistently crashes. Here is what I attempted: var template = domplate( { ...