1

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?

4
  • 1
    What have you tried so far? and what doesn't work? Commented Jun 11, 2021 at 10:21
  • 1
    I made you a snippet. Please edit it with relevant JavaScript you tried and expected output
    – mplungjan
    Commented Jun 11, 2021 at 10:24
  • @mplungjan Added the code.
    – Akhilesh
    Commented Jun 11, 2021 at 10:29
  • Parsing a timestamp in a specific timezone is possible but fairly complex to code yourself (e.g. here). Try a library like Luxon.
    – RobG
    Commented Jun 12, 2021 at 21:19

2 Answers 2

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

1
  • Thank you! I used the moment.js library.
    – Akhilesh
    Commented Jun 14, 2021 at 9:27
0

Coming back with a (hopefully) better answer.

This answer does something similar by converting each date with toLocaleString, then create 'new Date()' and then subtract the two. Eventually dividing by 6e4 to get the difference in minutes.

For the original example, we would have 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);

Not the answer you're looking for? Browse other questions tagged or ask your own question.