Skip to content

Instantly share code, notes, and snippets.

@danallison
Last active December 17, 2015 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danallison/5606496 to your computer and use it in GitHub Desktop.
Save danallison/5606496 to your computer and use it in GitHub Desktop.
Number of years, months, and days between today and some date in the past. Avoids problems associated with leap years and inconsistent total days in a given month.
var yearsMonthsDaysBetween = function(date) {
var andString, days, daysString, months, monthsString, s, today, years, yearsString;
today = new Date();
date = new Date(date);
years = today.getFullYear() - date.getFullYear();
months = today.getMonth() - date.getMonth();
days = today.getDate() - date.getDate();
if (days < 0) {
months -= 1;
days = Math.floor((today - new Date(today.getFullYear(), today.getMonth() - 1, date.getDate())) / 1000 / 60 / 60 / 24);
}
if (months < 0) {
years -= 1;
months += 12;
}
s = function(n) {
return ["s", "", "s"][Math.min(n, 2)];
};
yearsString = years ? "" + years + " year" + (s(years)) + ", " : "";
monthsString = months ? "" + months + " month" + (s(months)) + ", " : "";
andString = years + months ? "and " : "";
daysString = "" + days + " day" + (s(days));
return yearsString + monthsString + andString + daysString;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment