Skip to content

Calculating date difference in JavaScript is almost as easy as in PHP, but requires a bit different approach. For this post i wrote simple “static” js object which can calculate difference between two dates in: days, weeks, months and years.

To each function you pass two arguments/dates, the first one should be lower then second, or you will get negative number on the output, however the number will still be valid, although with negative sign, so you just need to multiply it by “-1”.

Calculating date difference in days and weeks works pretty much the same. First we get difference between UNIX timestamps for first and second dates and then divide it by number of milliseconds in a day (for days calculation), or by number of milliseconds in a week (for weeks calculation).

Number of milliseconds in a month vary (because months have different number of days), so we are taking a different approach. For each date multiply year by 12 and add current month, that gives total number of months since year 0. Now substract both numbers and we are done.

Calculating difference between years i leave without a comment :). Source code with example usage below.

```var DateDiff = {   inDays: function(d1, d2) { var t2 = d2.getTime(); var t1 = d1.getTime();   return parseInt((t2-t1)/(24*3600*1000)); },   inWeeks: function(d1, d2) { var t2 = d2.getTime(); var t1 = d1.getTime();   return parseInt((t2-t1)/(24*3600*1000*7)); },   inMonths: function(d1, d2) { var d1Y = d1.getFullYear(); var d2Y = d2.getFullYear(); var d1M = d1.getMonth(); var d2M = d2.getMonth();   return (d2M+12*d2Y)-(d1M+12*d1Y); },   inYears: function(d1, d2) { return d2.getFullYear()-d1.getFullYear(); } }   var dString = "May, 20, 1984";   var d1 = new Date(dString); var d2 = new Date();   document.write("<br />Number of <b>days</b> since "+dString+": "+DateDiff.inDays(d1, d2)); document.write("<br />Number of <b>weeks</b> since "+dString+": "+DateDiff.inWeeks(d1, d2)); document.write("<br />Number of <b>months</b> since "+dString+": "+DateDiff.inMonths(d1, d2)); document.write("<br />Number of <b>years</b> since "+dString+": "+DateDiff.inYears(d1, d2));```
Published inGeneral