Friday, March 29, 2024

How to Calculate the Difference between Two Dates in JavaScript

As mentioned in the Date Creation in JavaScript article, there are very few native date calculation functions in JavaScript. In fact, there are none other than to convert between local and UTC time. Left to their own devices, web developers have devised many ways of calculating date intervals, some of which are ingenious, while others are flawed or just plain wrong.

I’ve scoured the Internet for some of the very best date interval calculation formulas so that I may present them to you today in easy-to-use static Date functions. I hope you find them useful!

Adding and Subtracting from a Given Date

According to the documentation, Date setters expect an interval-appropriate value. The setDays() setter, for instance, expects a day from 1 to 31. But really, these ranges are nothing more than helpful recommendations because day values that lie outside of this range are rolled over/back into the next/preceding month(s). For example, attempting to assign a day of 30 to February causes the date to roll over into March:

var febDate  = new Date(2010, 1, 14); //Month is 0-11 in JavaScript
febDate.setDate(30);
console.log(febDate.toDateString()); //displays Tue Mar 2 2010

The same roll over behavior occurs in all the other setters and even accounts for leap years:

var y2k  = new Date(2000, 0, 1);
y2k.setMonth(14);

console.log('14 months after the new millenium is: ' + y2k.toDateString()); //displays Thu Mar 31 2001

var y2k  = new Date(2000, 0, 1);
y2k.setHours(-22);
console.log('22 hours before the new millenium is: ' + y2k); //displays Fri Dec 31 1999 02:00:00 GMT-0500 (Eastern Standard Time)

The roll over behavior presents us with the means to easily apply date intervals by supplying them directly to the appropriate setter:

var y2k  = new Date(2000, 0, 1);
y2k.setDate(y2k.getDate() + 88);

console.log('88 days after the new millenium is: ' + y2k.toDateString()); //displays Wed Mar 29 2000

Calculating the Difference between Two Known Dates

Unfortunately, calculating a date interval such as days, weeks, or months between two known dates is not as easy because you can’t just add Date objects together. In order to use a Date object in any sort of calculation, we must first retrieve the Date’s internal millisecond value, which is stored as a large integer. The function to do that is Date.getTime(). Once both Dates have been converted, subtracting the later one from the earlier one returns the difference in milliseconds. The desired interval can then be determined by dividing that number by the corresponding number of milliseconds. For instance, to obtain the number of days for a given number of milliseconds, we would divide by 86,400,000, the number of milliseconds in a day (1000 x 60 seconds x 60 minutes x 24 hours):

Date.daysBetween = function( date1, date2 ) {
  //Get 1 day in milliseconds
  var one_day=1000*60*60*24;

  // Convert both dates to milliseconds
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();

  // Calculate the difference in milliseconds
  var difference_ms = date2_ms - date1_ms;
    
  // Convert back to days and return
  return Math.round(difference_ms/one_day); 
}

//Set the two dates
var y2k  = new Date(2000, 0, 1); 
var Jan1st2010 = new Date(y2k.getFullYear() + 10, y2k.getMonth(), y2k.getDate());
var today= new Date();
//displays 726
console.log( 'Days since ' 
           + Jan1st2010.toLocaleDateString() + ': ' 
           + Date.daysBetween(Jan1st2010, today));

The rounding is optional, depending on whether you want partial days or not.

Converting Milliseconds to other Intervals

As long as you can calculate the number of milliseconds in an interval, you can come up with a number by dividing the total number of milliseconds by the number of milliseconds in the desired interval. What’s more, we can apply the modulus (%) operator to strip out that value to determine the next larger interval. The key is to always go from the smallest interval – milliseconds – to the largest – days:

Date.daysBetween = function( date1, date2 ) {
  //Get 1 day in milliseconds
  var one_day=1000*60*60*24;

  // Convert both dates to milliseconds
  var date1_ms = date1.getTime();
  var date2_ms = date2.getTime();

  // Calculate the difference in milliseconds
  var difference_ms = date2_ms - date1_ms;
  //take out milliseconds
  difference_ms = difference_ms/1000;
  var seconds = Math.floor(difference_ms % 60);
  difference_ms = difference_ms/60; 
  var minutes = Math.floor(difference_ms % 60);
  difference_ms = difference_ms/60; 
  var hours = Math.floor(difference_ms % 24);  
  var days = Math.floor(difference_ms/24);
  
  return days + ' days, ' + hours + ' hours, ' + minutes + ' minutes, and ' + seconds + ' seconds';
}

//Set the two dates
var y2k  = new Date(2000, 0, 1);
var Jan1st2010 = new Date(y2k.getYear() + 10, y2k.getMonth(), y2k.getDate());
var today= new Date();
//displays "Days from Wed Jan 01 0110 00:00:00 GMT-0500 (Eastern Standard Time) to Tue Dec 27 2011 12:14:02 GMT-0500 (Eastern Standard Time): 694686 days, 12 hours, 14 minutes, and 2 seconds"
console.log('Days from ' + Jan1st2010 + ' to ' + today + ': ' + Date.daysBetween(Jan1st2010, today));

A Simple dateDiff() Function

There is no reason to write a function for each date/time interval; one function can contain all of the required intervals and return the correct value for the one we want. In the following function, the datepart argument tells it what interval we are after, where ‘w’ is a week, ‘d’ a day, ‘h’ hours, ‘n’ for minutes, and ‘s’ for seconds:

 // datepart: 'y', 'm', 'w', 'd', 'h', 'n', 's'
Date.dateDiff = function(datepart, fromdate, todate) {	
  datepart = datepart.toLowerCase();	
  var diff = todate - fromdate;	
  var divideBy = { w:604800000, 
                   d:86400000, 
                   h:3600000, 
                   n:60000, 
                   s:1000 };	
  
  return Math.floor( diff/divideBy[datepart]);
}
//Set the two dates
var y2k  = new Date(2000, 0, 1);
var today= new Date();
console.log('Weeks since the new millenium: ' + Date.dateDiff('w', y2k, today)); //displays 625

A More Complete DateDiff() Function

Perhaps the above function looks like the Visual Basic function of the same name. In fact it is loosely based on it. I was planning on recreating it in its complete form for your enjoyment, but, thankfully someone has already beat me to it. That someone is Rob Eberhardt of Slingshot Solutions. It’s part of his excellent jsDate script. It’s free to use as long as you give credit where credit is due.

His function offers a lot of advantages over the simple one presented above. For starters, his can calculate the month interval, which cannot be done by dividing into the number of milliseconds since month lengths differ. It also supports setting the first day of the week to something other than Sunday. Finally, it adjusts for Daylight Savings Time, which affects intervals of a day (“d”) and larger:

Date.DateDiff = function(p_Interval, p_Date1, p_Date2, p_FirstDayOfWeek){
	p_FirstDayOfWeek = (isNaN(p_FirstDayOfWeek) || p_FirstDayOfWeek==0) ? vbSunday : parseInt(p_FirstDayOfWeek);

	var dt1 = Date.CDate(p_Date1);
	var dt2 = Date.CDate(p_Date2);

	//correct Daylight Savings Ttime (DST)-affected intervals ("d" & bigger)
	if("h,n,s,ms".indexOf(p_Interval.toLowerCase())==-1){
		if(p_Date1.toString().indexOf(":") ==-1){ dt1.setUTCHours(0,0,0,0) };	// no time, assume 12am
		if(p_Date2.toString().indexOf(":") ==-1){ dt2.setUTCHours(0,0,0,0) };	// no time, assume 12am
	}


	// get ms between UTC dates and make into "difference" date
	var iDiffMS = dt2.valueOf() - dt1.valueOf();
	var dtDiff = new Date(iDiffMS);

	// calc various diffs
	var nYears  = dt2.getUTCFullYear() - dt1.getUTCFullYear();
	var nMonths = dt2.getUTCMonth() - dt1.getUTCMonth() + (nYears!=0 ? nYears*12 : 0);
	var nQuarters = parseInt(nMonths / 3);
	
	var nMilliseconds = iDiffMS;
	var nSeconds = parseInt(iDiffMS / 1000);
	var nMinutes = parseInt(nSeconds / 60);
	var nHours = parseInt(nMinutes / 60);
	var nDays  = parseInt(nHours / 24);	//now fixed for DST switch days
	var nWeeks = parseInt(nDays / 7);

	if(p_Interval.toLowerCase()=='ww'){
			// set dates to 1st & last FirstDayOfWeek
			var offset = Date.DatePart("w", dt1, p_FirstDayOfWeek)-1;
			if(offset){	dt1.setDate(dt1.getDate() +7 -offset);	}
			var offset = Date.DatePart("w", dt2, p_FirstDayOfWeek)-1;
			if(offset){	dt2.setDate(dt2.getDate() -offset);	}
			// recurse to "w" with adjusted dates
			var nCalWeeks = Date.DateDiff("w", dt1, dt2) + 1;
	}
	
	// return difference
	switch(p_Interval.toLowerCase()){
		case "yyyy": return nYears;
		case "q": return nQuarters;
		case "m": return nMonths;
		case "y": // day of year
		case "d": return nDays;
		case "w": return nWeeks;
		case "ww":return nCalWeeks; // week of year	
		case "h": return nHours;
		case "n": return nMinutes;
		case "s": return nSeconds;
		case "ms":return nMilliseconds;
		default : return "invalid interval: '" + p_Interval + "'";
	}
}
var y2k  = new Date(2000, 0, 1) //Month is 0-11 in JavaScript!
var today= new Date();
console.log('Months since the new millenium: ' + Date.DateDiff('m', y2k, today)); //displays 143

Conclusion

All of these date calculations have been leading up to the final leg of this short series where we’ll be creating a form to calculate annualized returns of capital gains and losses. It will feature the new HTML5 Date Input control, as well as a jQuery widget fallback. But first, we will be creating some specialized functions to deal with leap years.

About the Author

Rob Gravelle resides in Ottawa, Canada, and is the founder of GravelleConsulting.com. Rob has built systems for Intelligence-related organizations such as Canada Border Services, CSIS as well as for numerous commercial businesses. Email Rob to receive a free estimate on your software project. Should you hire Rob and his firm, you’ll receive 15% off for mentioning that you heard about it here!

Robert Gravelle
Robert Gravelle
Rob Gravelle resides in Ottawa, Canada, and has been an IT guru for over 20 years. In that time, Rob has built systems for intelligence-related organizations such as Canada Border Services and various commercial businesses. In his spare time, Rob has become an accomplished music artist with several CDs and digital releases to his credit.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Popular Articles

Featured