252

So I have two dates YYYY-MM-DD and ZZZZ-NN-EE

How can I find out how many seconds there are between them?

Liam
  • 27,717
  • 28
  • 128
  • 190
steven
  • 13,147
  • 16
  • 39
  • 39
  • 203
    I try to leave at least a half-hour between dates to keep from getting caught. – Don Branson Jan 07 '10 at 22:37
  • 1
    `yyyy-MM-dd` is clear (year, month, day -note that they're not all uppercased), but ZZZZ-NN-EE not so. I interpret it as (timezone, ???, day-in-week). Is it week-in-year? If so, that would have been `ww`. But still then we need the year as well to calculate the difference. Can you please give some of the actual sample values? – BalusC Jan 07 '10 at 22:39
  • 8
    @BalusC: I believe he just went to the next letters to denote a second date (Y -> Z, M -> N, and D -> E). Using variable names such as startDate and endDate would probably have been better. – Austin Salonen Jan 07 '10 at 22:44
  • 1
    Ah, I see. This could indeed have been asked much clearer. – BalusC Jan 07 '10 at 22:50

10 Answers10

329

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)

Martin
  • 12,469
  • 13
  • 64
  • 128
  • 1
    Only the patterns used in the example aren't that right. 4-digit years is noted by lowercase `yyyy`, 2-digit months by uppercase `MM` and 2-digit days by lowercase `dd`. – BalusC Jan 07 '10 at 22:49
  • 1
    Martin, I have the impression that was not using any date patterns here. MM DD, YYYY and NN EE, ZZZZ are actually the "example values" that Steven asked. So in other words, he is not doing any kind for formatting. – Wagner Silveira Jan 07 '10 at 23:25
  • I have updated the second example, which is what I guess everyone was getting confused about. I've also added a bit of clarification as to exactly how I'm interpreting the values given in his example. – Martin Jan 08 '10 at 07:58
  • Your second variable need to be called `t2`. – Kees C. Bakker May 09 '12 at 20:21
  • In most cases you will probably be doing t2 - t1, not t1 - t2 – UpTheCreek Aug 10 '12 at 09:32
  • In this specific example it doesn't matter, since I take the absolute value of the subtraction – Martin Aug 10 '12 at 15:06
  • Depending on the situation `Math.round` might be a better choice. – gphilip Oct 01 '14 at 10:40
  • Absolutely, Math.Round(x) for an integer number of seconds, and Math.Round(Math.Abs(x)) for a positive integer number of seconds. – Martin Oct 01 '14 at 14:38
  • 6 years, 76 upvotes and 45886 views before someone finally notices the missing semicolons xD – Martin Nov 01 '15 at 02:47
115

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");
Liam
  • 27,717
  • 28
  • 128
  • 190
Seth
  • 45,033
  • 10
  • 85
  • 120
  • 1
    @user3344977 - then something funny is going on! Check the values of `a` and `b` and make sure that they're Dates. – Seth Oct 11 '16 at 16:33
  • 1
    @Seth you're correct so I deleted my comment.. one of my "dates" was actually a string. This works perfectly. – user3344977 Oct 11 '16 at 21:42
  • 1
    What is the difference between your answer (using just `new Date() - new Date()`) and @Martin's answer (using `new Date().getTime() - new Date().getTime()`)? – krummens Dec 18 '20 at 07:33
  • 1
    Answer to my own question from the previous comment: TypeScript doesn't like subtracting date objects from each other, giving this error: `The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.`. @Martin's answer, however, works in TypeScript. – krummens Dec 18 '20 at 08:03
  • 1
    I support using `getTime()` - the implicit coercion of the `new Date()` to a number might be by convention rather than by specification. I don't see operator behavior defined in the [spec](https://www.ecma-international.org/ecma-262/5.1/#sec-15.9). To me that suggests that the behavior is implicit based on coercion rules. I think being explicit (converting to milliseconds first so you know you're subtracting milliseconds) is much clearer. It would also immediately catch error that @user3344977 mentioned if a non-Date object gets accidentally sent into your function. – Seth Dec 18 '20 at 19:10
25

You can do it simply.

var secondBetweenTwoDate = Math.abs((new Date().getTime() - oldDate.getTime()) / 1000);
16

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

rmeador
  • 25,504
  • 18
  • 62
  • 103
  • 8
    +1 for mentioning the leap second issue! It's so frustrating when this gets mishandled, even by folks who ought to know better (POSIX committee, I'm lookin' at you...) – Jim Lewis Jan 07 '10 at 23:44
  • 3
    Worth mentioning that ECMA standard explicitly ignore leap seconds (i.e.: even *past* leap seconds): [In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.1). – Sylvain Leroux Dec 20 '15 at 09:42
6

create two Date objects and call valueOf() on both, then compare them.

JavaScript Date Object Reference

Jacob Relkin
  • 161,348
  • 33
  • 346
  • 320
6
var a = new Date("2010 jan 10"),
    b = new Date("2010 jan 9");

alert(
    a + "\n" + 
    b + "\n" +
    "Difference: " + ((+a - +b) / 1000)
);
Justin Johnson
  • 30,978
  • 7
  • 65
  • 89
6

Easy Way:

function diff_hours(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime()) / 1000;
  diff /= (60 * 60);
  return Math.abs(Math.round(diff));

 }


function diff_minutes(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime()) / 1000;
  diff /= (60);
  return Math.abs(Math.round(diff));

 }

function diff_seconds(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime()) / 1000;
  return Math.abs(Math.round(diff));

 }

function diff_miliseconds(dt2, dt1) 
 {

  var diff =(dt2.getTime() - dt1.getTime());
  return Math.abs(Math.round(diff));

 }


dt1 = new Date(2014,10,2);
dt2 = new Date(2014,10,3);
console.log(diff_hours(dt1, dt2));


dt1 = new Date("October 13, 2014 08:11:00");
dt2 = new Date("October 14, 2014 11:13:00");
console.log(diff_hours(dt1, dt2));

console.log(diff_minutes(dt1, dt2));

console.log(diff_seconds(dt1, dt2));

console.log(diff_miliseconds(dt1, dt2));
Fernando Pie
  • 895
  • 1
  • 12
  • 28
0
function parseDate(str) {
  const [dateStr, timeStr] = str.split(' ');
  const [m,d,y] = dateStr.split('/');
  const [h,min] = timeStr.split(':');
  const date = new Date(y,m,d,h,min,0, 0);
  
  return date;
}

const date1 = parseDate('28/6/2022 22:55');
const date2 = parseDate('28/6/2022 22:58');
const diffInSeconds = (date2 - date1) / 1000;

console.log(diffInSeconds)
-3

In bash:

bc <<< "$(date --date='1 week ago' +%s) - \
    $(date --date='Sun,  29 Feb 2004 16:21:42 -0800' +%s)"

It does require having bc and gnu date installed.

Alex G
  • 212
  • 1
  • 7
-12

.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
Jeff.Crossett
  • 315
  • 1
  • 10
  • @Jeff, you might want to delete this answer so you don't lose points. They asked for JavaScript source code, rather than Visual Basic source code. – JustBeingHelpful Sep 09 '14 at 19:13