Skip to content

Instantly share code, notes, and snippets.

@lemmon
Created May 16, 2016 14:27
Show Gist options
  • Save lemmon/d27c2d4a783b1cf72d1d1cc243458d56 to your computer and use it in GitHub Desktop.
Save lemmon/d27c2d4a783b1cf72d1d1cc243458d56 to your computer and use it in GitHub Desktop.
Calculates difference in years, months, and days between today and a date in past. Takes one string parameter -- date in YYYY-MM-DD format.
function dateDiff(date) {
date = date.split('-');
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth() + 1;
var day = today.getDate();
var yy = parseInt(date[0]);
var mm = parseInt(date[1]);
var dd = parseInt(date[2]);
var years, months, days;
// months
months = month - mm;
if (day < dd) {
months = months - 1;
}
// years
years = year - yy;
if (month * 100 + day < mm * 100 + dd) {
years = years - 1;
months = months + 12;
}
// days
days = Math.floor((today.getTime() - (new Date(yy + years, mm + months - 1, dd)).getTime()) / (24 * 60 * 60 * 1000));
//
return {years: years, months: months, days: days};
}
@xingkoo
Copy link

xingkoo commented Nov 19, 2016

mark

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment