How to calculate date difference in JavaScript? How to calculate date difference in JavaScript? javascript javascript

How to calculate date difference in JavaScript?


Assuming you have two Date objects, you can just subtract them to get the difference in milliseconds:

var difference = date2 - date1;

From there, you can use simple arithmetic to derive the other values.


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));

Code sample taken from here.


Another solution is convert difference to a new Date object and get that date's year(diff from 1970), month, day etc.

var date1 = new Date(2010, 6, 17);var date2 = new Date(2013, 12, 18);var diff = new Date(date2.getTime() - date1.getTime());// diff is: Thu Jul 05 1973 04:00:00 GMT+0300 (EEST)console.log(diff.getUTCFullYear() - 1970); // Gives difference as year// 3console.log(diff.getUTCMonth()); // Gives month count of difference// 6console.log(diff.getUTCDate() - 1); // Gives day count of difference// 4

So difference is like "3 years and 6 months and 4 days". If you want to take difference in a human readable style, that can help you.