Calculate the time difference in hours using time zone in Javascript

Within my JavaScript object, I have the following information:

var dateobj = {
  date: "2020-12-21 03:31:06.000000",
  timezone: "Africa/Abidjan",
  timezone_type: 3
}

var date = new Date();
var options = {
  timeZone: dateobj.timezone
};
var curr_date = date.toLocaleString('en-US', options)
console.log(curr_date)
//I desire to 
//diff = curr_date - dateobj.date

I am looking to calculate the time difference in hours between the current date-time and the specified timezone. While I understand that toLocaleString() can be used to obtain the date-time string in a specific timezone, I am unsure how to determine the time difference. The provided code retrieves the current date time within the timezone, but how do I go about calculating the time difference in hours?

Answer №1

When dealing with dates in JavaScript, I often rely on a library known as date-fns (Date functions) to simplify the management of dates and time. Here's an example of how you can calculate the time difference in hours using date-fns.

const { differenceInHours } = require("date-fns"); 
const { zonedTimeToUtc } = require("date-fns-tz");

const timeData1 = {date: "2020-12-21 03:31:06.000000", timezone: "Africa/Abidjan", timezone_type: 3};
const timeData2 = {date: "2020-12-21 03:31:06.000000", timezone: "America/Los_Angeles", timezone_type: 3};

const t1 = zonedTimeToUtc(timeData1.date, timeData1.timezone);
const t2 = zonedTimeToUtc(timeData2.date, timeData2.timezone);

const diff = differenceInHours(t2, t1);

console.log(diff);
// => 8

Try it out:

Answer №2

Returning with a hopefully improved response.

A similar method can be seen in this answer, where each date is converted using toLocaleString, a 'new Date()' instance is created, and then the two dates are subtracted. The result is then divided by 6e4 to obtain the difference in minutes.

For the given example, the approach would look something like this:

var dateobj = {
  date: "2020-12-21 03:31:06.000000",
  timezone: "Africa/Abidjan",
  timezone_type: 3
}

var date = new Date();
var options = {
  timeZone: dateobj.timezone
};

const curr_string = date.toLocaleString('en-US', options)
const orig_string = "12/21/2020, 03:31:06 AM"
const string1 = new Date(curr_string);
const string2 = new Date(orig_string);
console.log((string1.getTime() - string2.getTime()) / 6e4);

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

How to Retrieve JSON Object Using Dynamically Generated String in Angular

Creating a controller in Angular involves retrieving URL parts and parameters using $statePrams. The $http service is then called to retrieve data from a JSON file. Once the data is received, the content of a specific object element - determined by $state ...

mapStateToProps was invoked, however componentDidUpdate did not trigger

Working on fetching data for GameChart from an API and updating the Redux state. In my GameChart.jsx file, I have a chart that gets rendered when componentDidUpdate is called. However, there are times when changing the Redux state does not trigger componen ...

Displaying a single result in Angular from JSON without using the ng-repeat filter

Currently, I am working on developing an app to display news updates from a JSON API. The issue I am facing is that loading all the data from the JSON and filtering it using ng-repeat is causing slow performance, as there is a large amount of data. I woul ...

What is the best way to animate an element when it comes into the user's view

In order to activate the animation of the skill-bars when the element is displayed on the website, I am seeking a solution where scrolling down through the section triggers the animation. Although I have managed to conceptualize and implement the idea with ...

Utilizing the Masonry jQuery plugin for optimizing empty spaces

Recently, I came across the Masonry plugin and I'm considering using it in a project. One question that intrigues me is whether there is a way to detect empty spaces that occasionally show up in the layout when divs are positioned. Being able to ident ...

Steps to partially open the Modal Sheet Swipe Step by default

I've set up a modal sheet component with the following structure: <f7-sheet class="myClass" style="height: auto" swipe-to-step :backdrop="false" > <div class="sheet- ...

The anonymous function in the Google strategy is not being executed

I am currently working on implementing Passport to allow users to log in to my website using their Google accounts. I am utilizing yarn along with the following relevant packages: [email protected], and passport-google-oauth20@^1.0.0. The issue I am f ...

AssistanceBubble.js with ASP.NET UpdatePanel

Looking for guidance on implementing HelpBalloon.js () within an ASP.NET UpdatePanel. Experiencing issues with image loss after a postback. ...

Surprising Results when Using getBoundingClientRect()

Check out this code on CodePen In my current project, I'm attempting to position the footer div at the bottom of the page in such a way that it aligns with the maximum value of the bottom coordinates of both the menu and content divs (Math.max(menu, ...

Tips for updating the firebase access_token with the help of the next-auth credentials provider

Can anyone help me with refreshing the Firebase access token when it expires? I need the token for API authentication, but I can't find any information online regarding next-auth and Firebase. Currently, I am able to retrieve the access token but str ...

What is the process for configuring simultaneous services on CircleCI for testing purposes?

My current project involves running tests with Jasmine and WebdriverIO, which I want to automate using CircleCI. As someone new to testing, I'm a bit unsure of the process. Here's what I've gathered so far: To run the tests, I use npm tes ...

The error message "ECONNRESET" occurred while attempting to send a post request using Axios to

Attempting to send a post request to my webserver using axios, I have a client that collects user input to populate an array of strings. This data is then sent via a post request using axios for processing by the server: if (parsedInput > 0 &&am ...

Incorporate data from a CSV file into an HTML table on the fly with JavaScript/jQuery

I have a CSV file that is generated dynamically by another vendor and I need to display it in an HTML table on my website. The challenge is that I must manipulate the data from the CSV to show corrected values in the table, only displaying products and not ...

Uniquely tag an uploaded file

My code for uploading files is as follows: var xhr = new XMLHttpRequest(); xhr.upload.addEventListener("progress", uploadProgress, false); xhr.open("POST", requestUrl, true); xhr.send(f); I want to draw your attention to the fact that I have attached a l ...

Using Ajax to invoke a C# webmethod

I'm trying to call a webmethod defined in this specific class <%@ WebService Language="C#" Class="emt7anReyady.myService" %> using System; using System.Web; using System.Web.Services; using System.Web.Services.Protocols; using System.Linq; usi ...

The way an event can be outrun or vanish due to another event

let bar = new function(){ $scope.MessageSpan="Item added successfully";} When the Add button is clicked, the above function is invoked. However, if I want to hide this message when any other button is clicked, I would have to update the span text for all ...

error encountered in ajax contact form due to issue with select element

I'm experiencing an issue with my ajax contact form, where the input field and select element are not providing the expected results. This is the HTML Form Code (with "name" as the input and "iphone" as the select element) <div id="contact_form" ...

Harness the power of the ioHook Node.js global native keyboard and mouse listener within your Browser environment

I'm dealing with a challenging issue that seems to have no solution due to security limitations. However, I'm reaching out to you as my last hope to find a workaround. For my project, I require a system that can monitor user mouse and keyboard a ...

Navigate to a different HTML file following a JavaScript function in Ionic and AngularJS with Cordova

I am currently creating an Android application in Cordova Tools for Visual Studio using Ionic and AngularJS. My goal is to redirect to another HTML page once my function has completed its execution, but I'm having trouble getting it to work correctly ...

Outputting HTML with functions

I have a function that returns HTML code. renderSuggestion(suggestion) { const query = this.query; if (suggestion.name === "hotels") { const image = suggestion.item; return this.$createElement('div', image.title); } ...