It’s very often we come across requirement when we need to calculate time difference between two dates in Javascript. Here is a simple Javascript function which can do it in quick and dirty way :)

Dirty because I would have to say because I would have made it little more generalized by provide options and formats which convert string to date automatically..!

Anyway for that matter I would rather suggest using php.js which is interesting and helpful library which let’s us use lot of PHP functions in Javascript.. It includes hundreds of useful and handy functions which we are used to while we develop PHP Applications.

This simple functions takes only 2 arguments as Javascript Date objects and in return provides an object with days, hours, minutes and seconds as the property in difference between these 2 date provided as parameter to function.

Here is the code for simple Date-time difference calculation:

// Simple function to calculate time difference between 2 Javascript date objects
function get_time_difference(earlierDate,laterDate)
{
       var nTotalDiff = laterDate.getTime() - earlierDate.getTime();
       var oDiff = new Object();

       oDiff.days = Math.floor(nTotalDiff/1000/60/60/24);
       nTotalDiff -= oDiff.days*1000*60*60*24;

       oDiff.hours = Math.floor(nTotalDiff/1000/60/60);
       nTotalDiff -= oDiff.hours*1000*60*60;

       oDiff.minutes = Math.floor(nTotalDiff/1000/60);
       nTotalDiff -= oDiff.minutes*1000*60;

       oDiff.seconds = Math.floor(nTotalDiff/1000);

       return oDiff;

}
// Function Usage
function use_time_difference()
{
	dateWhenIndiaWonFirstCricketWorldCup = new Date(1983, 6, 25, 5, 0, 0);
	dateCurrent = new Date();
	oDiff = get_time_difference(dateWhenIndiaWonFirstCricketWorldCup, dateCurrent);
	alert("It has been " + oDiff.days + " days since India won it's first cricket worldcup");
}
use_time_difference();

Go see live demonstration or download and view source code.

I hope it would help some Javascript beginners.