How to define UTC timezone using numerical values in JavaScript [e.g. UTC+2, UTC+3, UTC-12, etc]

Is there a way to generate a date with a custom timezone such as UTC+2, UTC+3, UTC-12, etc without using string formats like 'America/New York' in JavaScript using moment.js? I have access to a list of timezones from the server in the format [UTC+2, UTC+3, UTC-12, etc] and I need to be able to create dates with a selected timezone. I attempted to utilize moment.js, but it only accepts string formats. Any suggestions for how to achieve this will be greatly appreciated. Thank you in advance!

Answer №1

I attempted to utilize the moment.js library but...

Have you explored these useful methods: .utc(), .add(), and .format() ?

EDIT

In order to handle non-full hour offsets, you can utilize .match to extract the sign (+ or -), the hour, and optionally the minute of the offset.

Refer to the complete list of possible offsets here: Wikipedia

If your offset is only UTC or an empty string, the output will be in UTC time.

const timeOffsets = ["UTC+2", "UTC+3", "UTC-12", "UTC+5:45", "UTC-3:30", "UTC", ""]

function getlocalTime(offset) {
  const time = offset.match(/([\+\-])(\d{1,2}):?(\d{2})?/)
  let sign = ""
  let numericOffset = 0
  if (time) {
    sign = time[1]
    numericOffset = parseInt(time[2]) + (time[3] ? parseInt(time[3]) / 60 : 0)
  }

  return moment().utc().add(sign + numericOffset, "hours").format("YYYY-MM-DD HH:mm:ss")
}

const result = timeOffsets.map(getlocalTime)

console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.4/moment.min.js"></script>

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

MongoDB's addToSet function does not include duplicates when adding values

I have a MongoDB collection that looks like this: [ { "acronym": "front", "references": [ { "date": "2020-03-04", "value": "5.6" }, { ...

The Angular JS field will only be considered valid if its value is more than zero

I have a text box in my form that changes its value dynamically when a user selects a category from a dropdown menu. Initially, the value is set to 0. $scope.validCats = "0"; HTML: <input ng-model="validCats" value="" type="text" class="form-control ...

Monitoring the validity or errors in AngularJS input fields

I'm attempting to observe the $error or $valid status of a control. Here is the control in question: <form id="myForm" name="myForm"> <input name="myInput" ng-model="myInputMdl" business-validation/> </form> The business-validat ...

Error message in React Js indicating the absence of a specified file or directory: "Package.json cannot

When I try to run npm start, I encounter the following error - PS D:\React\operations_app_tut> npm start npm ERR! path D:\React\operations_app_tut\package.json npm ERR! code ENOENT npm ERR! errno -4058 npm ERR! syscall open npm ...

Parsing XML to JSON using JavaScript

I came across this JavaScript function on Stack Overflow that I've been using to convert XML to JSON: function xmlToJson(xml) { try { var obj = {}; if (xml.nodeType == 1) { if (xml.attributes.length > 0) { ...

Traversing Through a Complicated JSON Structure

An application I developed can accept faxes in XML format and convert them into JSON objects to extract the necessary information, specifically the base64 string within the "file contents" variable of the document. Here is the code snippet: exports.recei ...

Client-side filtering of events in FullCalendar

I found a helpful answer on Stack Overflow that I am trying to use for client-side event filtering. While it works perfectly for newer events, I am facing an issue with filtering events that are loaded from JSON. Below is my JavaScript code: $(document) ...

The outcome is not displayed in the appropriate section of the text

There seems to be an issue as the console is not displaying the response to the input, such as "the answer is correct" or "the answer is either empty or incorrect". <!DOCTYPE html> <html lang="en"> <head> <title>Hello!</ ...

Tips for incorporating a hashbang into a JavaScript file that is executable without compromising browser compatibility

Is it possible to run code like this in both Node.js and the browser? #! /usr/local/bin/node console.log("Hello world") I have a script that I currently run locally in Node.js, but now I want to also execute it in the browser without having to modify it ...

Unable to dynamically translate special characters using npm latinize

When translating German special characters to English using latinize, the module only works when strings are passed within single or double quotes. However, it does not work when storing them inside a variable. import latinize from 'latinize'; ...

Is it possible to transform a ReadonlyArray<any> into a standard mutable array []?

At times, when working with Angular functions and callbacks, they may return a ReadonlyArray. However, I prefer using arrays in the traditional way and don't want to use immutable structures like those in Redux. So, what is the best way to convert a ...

Is it possible to implement PortalVue in multiple Vue.js single file components?

While working on Vue.js (single file components), I have discovered three methods of passing data around: local state/props, store, and utilizing PortalVue. Through my experiments with PortalVue, I successfully implemented both portal and portal-target wit ...

The combination of React.js and debouncing on the onChange event seems to be malfunctioning

I recently incorporated a React component that triggers an event on change. Here's how I did it: NewItem = React.createClass({ componentWillMount: function() { this._searchBoxHandler = debounce(this._searchBoxHandler, 500); }, _searchBoxH ...

Checking the availability of a username by sending an Ajax request every time the user types it may lead to inefficiencies and slower response times. Are there

I have developed a NodeJS authentication application. In this scenario, when a user enters a username, the system will display "username taken" if it is already in use, otherwise it will show "username available". I am interested in understanding the lim ...

What is the correct way to invoke a function contained within an object that is stored in an array?

I've encountered a problem with my program. I'm attempting to invoke a function that is part of an object stored in an array, but I'm having difficulty calling the function correctly. //Initialize Array for Storing Projects let allProjects ...

Encountering an error message that states "Unable to access property 'props' of null object while filling

Can anyone help me figure out the error in my React component code below? import React, { Component } from 'react'; import { Input} from 'antd'; import Form from '../../components/uielements/form'; import Button from '.. ...

Error retrieving Facebook access token using Node.js https.get()

I've been working on setting up a Facebook login flow in my node.js app, but I'm facing an issue where the access token isn't returning from the Facebook API when using node's https.get() method. Interestingly, I am able to retrieve the ...

"Utilizing Regular Expressions and For Loops to Manipulate Strings: Splitting and

I am struggling to create a regular expression that can transform a string formatted like (person,item(bought,paid),shipping(address(city,state))) into a different format like this: person item * bought * paid shipping * address ** city ** state My curr ...

Transform a value nested at any depth into an object key using Ramda or plain JavaScript

I have encountered a unique scenario while using a specific library. Instead of returning an array, this library returns nested objects with the final leaf node containing the value. For instance: red.walk.fast.true is returned as {red: {walk: {fast: &apo ...

Small jumps occur when implementing the scrollTop jquery animation

I've encountered an issue with the scrollTop jquery animation that I can't seem to resolve. It seems to micro-jump right before the animation, especially when there is heavier content. I'm puzzled as to why this is happening... Here's ...