How do I calculate how many seconds between two dates?
Solution 1:
I'm taking YYYY & ZZZZ to mean integer values which mean the year, MM & NN to mean integer values meaning the month of the year and DD & EE as integer values meaning the day of the month.
var t1 = new Date(YYYY, MM, DD, 0, 0, 0, 0);
var t2 = new Date(ZZZZ, NN, EE, 0, 0, 0, 0);
var dif = t1.getTime() - t2.getTime();
var Seconds_from_T1_to_T2 = dif / 1000;
var Seconds_Between_Dates = Math.abs(Seconds_from_T1_to_T2);
A handy source for future reference is the MDN site
Alternatively, if your dates come in a format javascript can parse
var dif = Date.parse(MM + " " + DD + ", " + YYYY) - Date.parse(NN + " " + EE + ", " + ZZZZ);
and then you can use that value as the difference in milliseconds (dif in both my examples has the same meaning)
Solution 2:
Just subtract:
var a = new Date();
alert("Wait a few seconds, then click OK");
var b = new Date();
var difference = (b - a) / 1000;
console.log("You waited: " + difference + " seconds");
Solution 3:
You can do it simply.
var secondBetweenTwoDate = Math.abs((new Date().getTime() - oldDate.getTime()) / 1000);
Solution 4:
If one or both of your dates are in the future, then I'm afraid you're SOL if you want to-the-second accuracy. UTC time has leap seconds that aren't known until about 6 months before they happen, so any dates further out than that can be inaccurate by some number of seconds (and in practice, since people don't update their machines that often, you may find that any time in the future is off by some number of seconds).
This gives a good explanation of the theory of designing date/time libraries and why this is so: http://www.boost.org/doc/libs/1_41_0/doc/html/date_time/details.html#date_time.tradeoffs