Labels

Sunday, January 18, 2015

Javascript: Date difference in years and months


The code below subtracts 2 dates in Javascript and outputs the difference as years and months.

function msToYears(ms){
var numYears = ms/(3600000*24*365);
var numMonths = numYears - Math.floor(numYears);
return Math.floor(numYears)+'y'+Math.round((numMonths * 12))+'m';
}

var d1 = new Date(2014,09,01);
var d2 = new Date(2014,12,23);
var numYears = msToYears(Math.abs(d1 -d2));
console.log(numYears);

No comments:

Post a Comment