Skip to content

Instantly share code, notes, and snippets.

@jovannic
Created August 12, 2014 22:32
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 jovannic/552d57e4bf41e8413f34 to your computer and use it in GitHub Desktop.
Save jovannic/552d57e4bf41e8413f34 to your computer and use it in GitHub Desktop.
Consistent, Exact Aniversary Counter
var YEAR = 31536000000;
var DAY = 86400000;
var HOUR = 3600000;
var MINUTE = 60000;
var SECOND = 1000;
/**
* Takes two date objects and returns the time difference of the present date
* since the past date.
* @param {Date} past The past date
* @param {Date} present The presetn date
* @returns {years: number, months: number, hours: number, minutes: number, seconds: number, milliseconds: number}
*/
function timeSince(past, present) {
var pastMonthStart = new Date(past.getFullYear(), past.getMonth());
var pastIntoMonth = past.getTime() - pastMonthStart.getTime();
var monthStart = new Date(present.getFullYear(), present.getMonth());
// milliseconds into the current month
var milliseconds = present.getTime() - monthStart.getTime();
// whole calendar months past
var monthsPast = (present.getFullYear() - past.getFullYear()) * 12 + (present.getMonth() - past.getMonth() - 1);
// another if gone past anniversary in the current month
if (milliseconds > pastIntoMonth) {
milliseconds -= pastIntoMonth;
monthsPast++;
}
// a year is 12 months, whatever a month may be
var years = Math.floor(monthsPast / 12);
var months = monthsPast % 12;
var days = Math.floor(milliseconds / DAY);
milliseconds -= days * DAY;
var hours = Math.floor(milliseconds / HOUR);
milliseconds -= hours * HOUR;
var minutes = Math.floor(milliseconds / MINUTE);
milliseconds -= minutes * MINUTE;
var seconds = Math.floor(milliseconds / SECOND);
milliseconds -= seconds * SECOND;
return {
years: years,
months: months,
hours: hours,
minutes: minutes,
seconds: seconds,
milliseconds: milliseconds
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment