Skip to content

Instantly share code, notes, and snippets.

@caugner
Created October 31, 2014 14:26
Show Gist options
  • Save caugner/55f9294fc9a0bc826f01 to your computer and use it in GitHub Desktop.
Save caugner/55f9294fc9a0bc826f01 to your computer and use it in GitHub Desktop.
Determine intuitive difference between two dates
function date_difference(from_date, to_date) {
if (to_date < from_date) {
return date_difference(to_date, from_date);
}
var DAY_IN_MS = 1000 * 60 * 60 * 24;
// count first day
from_date = new Date(from_date.getTime() - DAY_IN_MS);
var days = 0;
var months = 0;
var years = 0;
// count years
while (true) {
var year = from_date.getFullYear() + 1;
var new_date = new Date(from_date.getTime());
new_date.setFullYear(year);
if (new_date < to_date) {
years++;
from_date = new_date;
} else {
break;
}
}
// count months
while (true) {
var new_date = new Date(from_date.getTime());
var month = from_date.getMonth() + 1;
if (month == 12) {
var year = from_date.getFullYear() + 1;
new_date.setFullYear(year);
month = 0;
}
new_date.setMonth(month);
if (new_date < to_date) {
months++;
from_date = new_date;
} else {
break;
}
}
// count days
while (true) {
var new_date = new Date(from_date.getTime() + DAY_IN_MS);
if (new_date < to_date) {
days++;
from_date = new_date;
} else {
break;
}
}
return [years, months, days];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment