Ari
Ari

Reputation: 6199

What is the result type of subtracting a date from another date?

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?

Upvotes: 1

Views: 71

Answers (4)

ifelse.codes
ifelse.codes

Reputation: 2389

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) 

Upvotes: 1

user12956752
user12956752

Reputation:

Output will be number of milliseconds.

Upvotes: 1

Andrew
Andrew

Reputation: 446

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.

Upvotes: 1

Adam M.
Adam M.

Reputation: 1088

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)

Upvotes: 1

Related Questions