views:

259

answers:

4

how to find difference between two dates

+2  A: 

First result on Google :)

keyboardP
+6  A: 

By using the Date object:

var a = new Date(); // Now
var b = new Date(2010, 0, 1, 0, 0, 0, 0); // 2010
var d = (b-a); // difference in milliseconds

You can get the number of seconds by dividing the milliseconds by 1000, and rounding the number:

var seconds = Math.round((b-a)/1000);

You could then get minutes by again dividing seconds by 60, then hours by dividing minutes by 60, then days by dividing hours by 24, etc.

You'll note that I provided some values for the second Date object. Those parameters are as follows:

// new Date(year, month, day, hours, minutes, seconds, milliseconds)

As noted in the comments of this solution, you don't necessarily need to provide these values unless they're necessary for the date you wish to represent.

Jonathan Sampson
You don't need to call the `Date` constructor with all the arguments, you can call it only with Year and Month, the other arguments are optional.
CMS
Thanks, CMS. I wanted to be sure the user understood that they can get very granular with their specification.
Jonathan Sampson
I've updated the solution to communicate your point, CMS. I appreciate the heads-up.
Jonathan Sampson
You're welcome Jonathan, thanks for the edit... also note that `b` is actually 2009-12-31, since a `0` was used as the day argument, it can be somehow confusing for the newcomer...
CMS
Ah, good eye, CMS. The month is zero-based, if I'm not mistaken. A bit confusing indeed.
Jonathan Sampson
+2  A: 

Use DateJs.

Swiss knife tool for javascript date-time prgoramming!

http://www.datejs.com/

this. __curious_geek
A: 
    // This is for first date
    first = new Date(2010, 03, 08, 15, 30, 10); // Get the first date epoch object
    document.write((first.getTime())/1000); // get the actual epoch values
    second = new Date(2012, 03, 08, 15, 30, 10); // Get the first date epoch object
    document.write((second.getTime())/1000); // get the actual epoch values
    diff= second - first ;
    one_day_epoch = 24*60*60 ;  // calculating one epoch
    if ( diff/ one_day_epoch > 365 ) // check , is it exceei
    {
    alert( 'date is exceeding one year');
    }
pavun_cool