So I have two dates YYYY-MM-DD and ZZZZ-NN-EE
How can I find out how many seconds there are between them?
So I have two dates YYYY-MM-DD and ZZZZ-NN-EE
How can I find out how many seconds there are between them?
create two Date
objects and call valueOf()
on both, then compare them.
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 t1 = 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 w3schools 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)
Just subtract:
var a = new Date();
alert("Wait a few seconds, then click OK");
var b = new Date();
var difference = (b - a) / 1000;
alert("You waited: " + difference + " seconds");
var a = new Date("2010 jan 10"),
b = new Date("2010 jan 9");
alert(
a + "\n" +
b + "\n" +
"Difference: " + ((+a - +b) / 1000)
);
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
.Net provides the TimeSpan class to do the math for you.
var time1 = new Date(YYYY, MM, DD, 0, 0, 0, 0)
var time2 = new Date(ZZZZ, NN, EE, 0, 0, 0, 0)
Dim ts As TimeSpan = time2.Subtract(time1)
ts.TotalSeconds