Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to calculate date difference in Javascript

Tags:

javascript

I doing a function in Javascript like the VisualBasic DateDiff.

You give two dates and the returning time interval (Seconds, Minutes, Days, etc...)

DateDiff(ByVal Interval As Microsoft.VisualBasic.DateInterval, _   ByVal Date1 As Date, ByVal Date2 As Date) as Long 

So what's the best way to calculate the difference of Javascript Dates?

like image 809
InfoStatus Avatar asked Nov 29 '08 11:11

InfoStatus


People also ask

Can we subtract two dates in JavaScript?

Here, first, we are defining two dates by using the new date(), then we calculate the time difference between both specified dates by using the inbuilt getTime(). Then we calculate the number of days by dividing the difference of time of both dates by the no. of milliseconds in a day that are (1000*60*60*24).

How do I calculate the difference between two dates in TypeScript?

To calculate the time between 2 dates in TypeScript, call the getTime() method on both dates when subtracting, e.g. date2. getTime() - date1. getTime() . The getTime() method returns a number representing the milliseconds between the unix epoch an the given date.


1 Answers

Use the Date object like so:

function DateDiff(var /*Date*/ date1, var /*Date*/ date2) {     return date1.getTime() - date2.getTime(); } 

This will return the number of milliseconds difference between the two dates. Converting it to seconds, minutes, hours etc. shouldn't be too difficult.

like image 67
Anand Avatar answered Sep 23 '22 16:09

Anand