Skip to content

Instantly share code, notes, and snippets.

@matheushrt
Created February 6, 2020 18:34
Show Gist options
  • Save matheushrt/c5151e379b51fdec80feeb93b451d61b to your computer and use it in GitHub Desktop.
Save matheushrt/c5151e379b51fdec80feeb93b451d61b to your computer and use it in GitHub Desktop.
Getting elapsed time with vanilla Javascript based on milliseconds, not using Date methods.
function getAge(birthDate, dateToCompare) {
const birth = new Date(birthDate);
const dateToCheck = dateToCompare ? new Date(dateToCompare) : new Date();
const [initialYear, finalYear] = [birth.getFullYear(), dateToCheck.getFullYear()];
// getting milliseconds passed from birthdate to the date to check
const milliseconds = dateToCheck.valueOf() - birth.valueOf();
// returning age by transforming milliseconds => minutes => hours => days => years
const age = milliseconds / (1000 * 60 * 60 * 24 * averageDaysPerYear(initialYear, finalYear));
return parseInt(age);
}
function leapYearsCounter(initialYear, finalYear) {
let count = 0;
for (let year = initialYear; year <= finalYear; year++) {
if (!(year % 4)) count++;
else if (!(year % 100) && !(year % 400)) count++;
}
return count;
}
function averageDaysPerYear(initialYear, finalYear) {
const leapYearsCount = leapYearsCounter(initialYear, finalYear);
const years = finalYear - initialYear;
const average = ((years - leapYearsCount) * 365 + leapYearsCount * 366) / years;
return average;
}
const age = getAge('1985.11.03', '2020.11.02');
console.log(age); // 34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment