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

pressing a button unrelated to the 'close' button still triggers the close event

I have a notification bar that features a button in the center that links to another website. There is also a 'close' button on the far right. However, whenever I click the center button, it also triggers the close button. I tried moving the #cl ...

The sweetalert 2 input field is unresponsive or disabled within a materializecss modal, making it impossible to type in

My modal includes a SweetAlert2 popup when I click the "add bills" button. The code for this feature is from their documentation, so I don't believe the issue lies there. However, I am experiencing a problem where the input field is not type-able and ...

Adjusting the alignment of a facial image on Canvas by selecting specific click-points

I have a unique idea for an app that allows users to correct a tilted face with just 2 clicks The concept is simple - users click on the middle of the nose and the middle of the eyebrows within the image to generate two points: eyebrowMiddle(x1,y1) and no ...

When the user presses the enter key to submit data, the Ajax page reloads

I am facing an issue with a simple form for sending messages from one person to another using AJAX method POST to prevent page reload. The problem arises when the user hits [ENTER] in the field, causing the page to reload instead of the AJAX working as int ...

When attempting to send an email using the emailjs.send function, an unexpected error occurred showing the URL https://api.emailjs.com/api/v1.0/email/send with a

import emailjs from 'emailjs-com'; async function sendEmail() { try { const serviceID = '...'; const templateID = '...'; const userID = '...'; const emailParams = { to_email: '...&a ...

Displaying Modal from a separate component

CardComponent: export class Card extends Component<Prop, State> { state = { isCancelModalOpen: false, }; marketService = new MarketService(); deleteMarket = () => { this.marketService .deleteMar( ...

Finding common elements between two arrays through partial matching

Imagine I have two arrays: var array_full = ['table', 'sleeping', 'data']; var array_part = ['sleep', 'able']; My goal is to extract items from the full string array (array_full) that do not contain any e ...

What is the most effective method for incorporating multi-line breadcrumb links in a React application?

I am currently working on implementing a multiline breadcrumb link feature for mobile and tablet devices. As users navigate through multiple folders, I need to handle scenarios where the number of links exceeds the maximum allowed in the breadcrumb contain ...

Using TypeScript to define callback functions within the Cordova.exec method

I'm encountering an issue with the TypeScript definition for Cordova. The codrova.d.ts file doesn't allow for any function arguments in the success-callback and error-callback. To better illustrate my problem, here's a small example: Here ...

Leveraging Javascript/Jquery for numbering items in a list

This is a snippet of HTML code that I am working with: <ul> <li data-slide-to="0" data-target="#myCarousel" class="appendLi"></li> <li data-slide-to="0" data-target="#myCarousel" class="appendLi"></li> <li data ...

Using the concept of method chaining in JavaScript, you can easily add multiple methods from

Hey there! I'm looking for some assistance with dynamically building a method chain. It seems like it should be pretty straightforward if you're familiar with how to do it... Currently, I am using mongoose and node.js to query a mongo database. ...

Go through each .md document, transform them into HTML format, and dispatch them

I am using fs to read files in .md format and transform them into HTML files. Here is the code snippet I have written: fs = require('fs'); fs.readFile(__dirname + '/posts/react-v16.13.0.md', 'utf8', function (err, data) { i ...

I encountered a TS error warning about a possible null value, despite already confirming that the value

In line 5 of the script, TypeScript raises an issue regarding the possibility of gameInstanceContext.gameInstance being null. Interestingly, this concern is not present in line 3. Given that I have verified its existence on line 1, it is perplexing as to w ...

Preserve the existing value and then check it against the updated value of a variable within JavaScript

I utilized an API that supplies me with information in JSON format, retrieved the price of a specific currency, and presented it on a screen using JavaScript. I encapsulated this process within a function that dynamically updates the information at set int ...

The asynchronous callbacks or promises executing independently of protractor/webdriver's knowledge

Could a log like this actually exist? 07-<...>.js ... Stacktrace: [31m[31mError: Failed expectation[31m [31m at [object Object].<anonymous> (...06-....js)[31m[31m[22m[39m It seems that something is failing in file -06- while I am processin ...

Experiencing difficulties replicating two auto-scrolling divs

I have implemented a script to automatically slide two different divs. Here is the code I am using: The HTML: <div id="gallery"> <div id="slider" style="width: 6000px; left: -500px;"> <div><aside class="widget widget_testimoni ...

Struggling with converting 11-line toy neural network code into JavaScript

I'm preparing to deliver a brief presentation on neural networks this coming Tuesday to my fellow web developer students. My plan was to convert this code (found under Part 1, a tiny toy neural network: 2 layer network) into JavaScript so that it woul ...

What is the best way to utilize multiple models under a single root in ReactJS?

Greetings! I currently have a root structure in the following code snippet: <body> <noscript>You need to enable JavaScript to run this app.</noscript> <button >Platform</button> <button >Game</button> < ...

Retrieve the subdomain from within the passport FacebookTokenStrategy and GoogleStrategy

In the process of developing a node.js application with wildcard subdomains, I am creating separate parts of the app for each subdomain that will have distinct user authentication based on the subdomain. For instance, envisioning my app having subdomains ...

What is the best way to ensure the remaining PHP script is executed after using json_encode()?

My current project involves creating a form with four input fields: name, email, phone, and message. To handle the submission process, I am utilizing JavaScript in conjunction with Ajax to send the user inputs to a PHP file for validation and mailing using ...