What is the best way to calculate a date difference?

What's the best way to calculate date difference in 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?

  • Answer:

    Use the http://w3schools.com/jsref/jsref_obj_date.asp 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.

DK39 at Stack Overflow Visit the source

Was this solution helpful to you?

Other answers

If you follow this http://www.javascriptkit.com/javatutors/datedifference.shtml, one way is to use: Date.getTime() You will find a full http://javascript.internet.com/math-related/date-difference.html, complete with date validation.

VonC

Javascript source code to do exactly that can be found http://javascript.internet.com/math-related/date-difference.html

Paul

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.