Created
February 6, 2020 18:34
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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