Categories
JavaScript Answers

How to Get the Number of Minutes Between Two Dates with JavaScript?

Spread the love

Sometimes, we want to get the number of minutes between 2 dates with JavaScript.

In this article, we’ll look at how to get the number of minutes between 2 dates with JavaScript.

Subtract 2 Dates After Converting the Dates to Timestamps and Convert the Difference to Minutes

We can convert JavaScript date objects to timestamps, subtract them, and then convert the difference to minutes.

To do this, we write:

const d2 = new Date(2020, 2, 1);  
const d1 = new Date(2020, 1, 1);  
const diffMs = +d2 - +d1;  
const diffMins = Math.floor((diffMs / 1000) / 60);  
console.log(diffMins)

We have the d2 and d1 date objects, which we want to get the difference in minutes between.

In the 3rd line, we convert the d2 and d1 date objects to timestamps in milliseconds with the + operator in front of them.

Then we divide diffMs by 1000 to convert the difference in seconds.

And then we divide that by 60 to convert it to minutes.

Then from the console log, we should see the number of minutes difference between d2 and d1 is 41760.

We can also convert d2 and d1 to timestamps with the getTime method.

For instance, we can write:

const d2 = new Date(2020, 2, 1);  
const d1 = new Date(2020, 1, 1);  
const diffMs = d2.getTime() - d1.getTime();  
const diffMins = Math.floor((diffMs / 1000) / 60);  
console.log(diffMins)

And we get the same result as before.

Conclusion

We can get the difference between 2 dates in minutes by converting to timestamps in milliseconds, subtract the 2 timestamps, and convert the difference to minutes.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *