1

I have two Date() objects, lets say for example date A is yesterday and date B is todays date. The end purpose is to find how much time occured between these two dates. So I subtract date A from date B

let dateA = new Date("2020-02-23T00:00:00.000Z")
let dateB = new Date("2020-02-24T00:00:00.000Z")

let timeDifference = dateB - dateA
console.log(timeDifference)

What is the output type of this? is it milliseconds, seconds? unixtimestamp?

What would be the best way to display how much time occured in a user friendly way, moment.js?

Ari
  • 5,301
  • 8
  • 46
  • 120
  • Does this answer your question? [Get difference between 2 dates in JavaScript?](https://stackoverflow.com/questions/3224834/get-difference-between-2-dates-in-javascript) – EternalHour Feb 24 '20 at 22:52
  • 1
    Doing a subtraction always converts the operands to numbers, which [in case of `Date`s](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/valueOf) does yield the number of milliseconds since unix epoch. – Bergi Feb 24 '20 at 22:56

4 Answers4

1

https://momentjs.com/docs/#/displaying/from/

var a = moment(new Date("2020-02-23T20:20:00.000Z"));
var b = moment(new Date("2020-02-24T00:10:00.000Z"));
a.from(b)        // "4 hours ago"
a.from(b,true)  // "4 hours"

Using minus(-) operator on Date will convert date into milliseconds and perform the substation so the output will be milliseconds.

let dateA = new Date("2020-02-23T00:00:00.000Z")
let dateB = new Date("2020-02-24T00:00:00.000Z")
let timeDifference = dateB - dateA
console.log(timeDifference) // 86400000 (milliseconds) 
ifelse.codes
  • 2,289
  • 23
  • 21
  • Brilliant, I'll give it a go. – Ari Feb 24 '20 at 22:53
  • javascript date minus give you in miliseconds – ifelse.codes Feb 24 '20 at 22:54
  • Works, my only issue is I'd like my output to be worded more like eg. "8 days", rather than say "8 days ago", as it's the amount of time passed, not a reference. But thats okay I'll read the moment.js documentation to see what I can use. Thanks! – Ari Feb 24 '20 at 22:57
  • edited your answer to show the part that gave me the output I needed, thanks again. – Ari Feb 24 '20 at 23:06
1

It is the number of milliseconds. The result that you have from your example is 86400000, it is the number of milliseconds in one day.

1000 (milliseconds) * 60 (seconds in a minute) * 60 (minutes in one hour) * 24 (hours in a day)

Adam M.
  • 1,071
  • 1
  • 7
  • 23
1

The output is the millisecond difference between the two dates - in this case, 24 hours, or 86400000 milliseconds. And you really don't need an entire library to render that in a human-readable format.

Andrew
  • 436
  • 3
  • 7
1

Output will be number of milliseconds.