-1

Does anyone know how to calculate the difference between two datetimes in Javascript ?

For example: 2018-01-17T21:18:00 and 2018-01-16T21:17:00

I tried to split them and add them together afterwards but I noticed the hours are already calculated in the date difference.

Why don´t people understand the simple difference between date and datetime ? Stop Voting down, or writing stuipid comments.

Deadpool
  • 210
  • 3
  • 14

2 Answers2

2

use Math.abs if you would get a negative value (ie if you don't know if a is lower then b)

Date object is essentially a number and you can do mathematical operations with it without getting timestamp

var a = new Date('2018-01-17T21:18:00')
var b = new Date('2018-01-16T21:17:00')

console.log(a - b) // possible use
console.log(Math.abs(a - b)) // safe to use
console.log(Math.abs(b - a)) // safe to use
console.log(b - a) // not what you want

from there you just calculate how many days/hours/min there is

Endless
  • 34,080
  • 13
  • 108
  • 131
  • 1
    If you know for sure that `a` is bigger then `b` you don't need `Math.abs` (just do `a - b`) – Endless Jan 20 '18 at 19:20
  • oh ok, great thanks, I didn't expect it to be that simple – Deadpool Jan 20 '18 at 20:08
  • *Date object is essentially a number* — uhh, no, it's not. There's a `.valueOf()` function on its prototype that returns the same value as its `.getTime()` function, so that it works with arithmetic operators like a number, but it's an object. – Pointy Jan 21 '18 at 16:02
0

you can use valueOf -> https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf

let date1 = new Date('2018-01-17T21:18:00')
let date2 = new Date('2018-01-16T21:17:00')
//you get the difference in ms
let difference = Math.abs(date1.valueOf()-date2.valueOf())
//you can then convert to any format
nitte93
  • 1,820
  • 3
  • 26
  • 42
  • You don't need to use `valueOf` thanks to `valueOf` existence [read differens](https://stackoverflow.com/questions/9710136/in-javascript-why-do-date-objects-have-both-valueof-and-gettime-methods-if-they) – Endless Jan 20 '18 at 19:28