0

I want to subtract two dates to get the difference between them. Hours and minutes are what interests me. The two dates will always be on the same day.

I have the following code:

const differenceAsDate = new Date(toTime.getTime() - fromTime.getTime());

Let's assume that toTime = Wed Mar 18 2020 07:00:00 GMT+0100 and fromTime = Wed Mar 18 2020 08:00:00 GMT+0100 so they are one hour apart.

This resulting date is Thu Jan 01 1970 02:00:00 GMT+0100. How can I fix this?

nick zoum
  • 7,216
  • 7
  • 36
  • 80
Nexonus
  • 706
  • 6
  • 26
  • That's right, isn't it? They're an hour apart, which would be 1am on January 1st, 1970 as a "date", but *you're in GMT+1*, so it would be 2am for you. The question is more why you're using a Date as a delta – jonrsharpe Mar 18 '20 at 21:00
  • But I would assume that when subtracting two dates which have GMT +1, the resulting GMT+1 date would not include the GMT+1 in the hours, if you know what I mean. – Nexonus Mar 18 '20 at 21:01
  • Subtraction doesn't give you a date, though, it gives you a number of milliseconds. Then you convert that to a date, from the start of the epoch *in GMT*. – jonrsharpe Mar 18 '20 at 21:02
  • But then how do I do it correctly? I have not found another class or way for just working with the time, not the date. – Nexonus Mar 18 '20 at 21:03
  • Converting milliseconds to hours and minutes is just basic maths - `value / (1000 * 60 * 60)` hours and `(value / (1000 * 60)) % 60` minutes. Or use something that can represent a delta/duration like Moment: https://momentjs.com/docs/#/durations/ (or not Moment https://github.com/you-dont-need/You-Dont-Need-Momentjs). – jonrsharpe Mar 18 '20 at 21:05
  • I got it working with `value / (1000 * 60 * 60)` and such. Thanks for the fast help! – Nexonus Mar 18 '20 at 21:15

1 Answers1

1

You can subtract your time, and then get minute and hour by this code:

const differenceAsDate = Math.abs(toTime.getTime() - fromTime.getTime());
const minute = (differenceAsDate / 6e4)%60;
const hour = parseInt((differenceAsDate / 36e5), 10);

console.log({hour, minute});
Alireza HI
  • 1,873
  • 1
  • 12
  • 20
  • Thanks! This works perfectly fine but I get two TSLint complaints in IntelliJ. One being a missing radix as a parameter for `parseInt()` and the other being `Argument of type 'number' is not assignable to parameter of type 'string'`. I wrote that I work in Typescript, but someone seem to have edited my answer and removed it. – Nexonus Mar 18 '20 at 21:19
  • 1
    For the `radix` problems use parseInt as this: `parseInt((differenceAsDate/36e5), 10)` – Alireza HI Mar 18 '20 at 21:22
  • and for the second one you need to change of your parameters that are defined as `string` to `number`. – Alireza HI Mar 18 '20 at 21:23
  • 1
    Barfing over a missing radix in `parseInt(differenceAsDate / 36e5, 10)` is pedantry in the extreme. `differenceAsDate / 36e5 | 0` is less to type and likely the linter is happy. – RobG Mar 20 '20 at 05:11