0

I have a javascript object with the following details:

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 want this 
//diff = curr_date - dateobj.date

I want to find the time difference in hours with the current date-time of the same timezone. I know I can use toLocaleString() function to get the date-time string in a particular timezone, but how can I find the time difference? The above code gets the current date time in that timezone, how can I find the time difference in hours?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
Akhilesh
  • 1,243
  • 4
  • 16
  • 49

1 Answers1

1

In general when working with dates in JS I usually use a library called date-fns (Date functions). It just makes dates and time a lot easier to manage. This is how you would get the time difference in hours with 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

Run demo: https://runkit.com/embed/jtfu0ixxthy7

Olian04
  • 6,480
  • 2
  • 27
  • 54