Categories
discuss

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….

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 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.

Source: stackoverflow
Text is available under the Creative Commons Attribution-ShareAlike License; additional terms may apply. By using this site, you agree to the Privacy Policy, and Copyright Policy. Content is available under CC BY-SA 3.0 unless otherwise noted. The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 © No Copyrights, All Questions are retrived from public domain..