Last active
August 6, 2019 01:03
-
-
Save locmai0808/09616c45ca482ed4156c05193b75bb5a to your computer and use it in GitHub Desktop.
Code to convert birthdate in months/years to age in months/years and vice versa
This file contains 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
/* Converts between age in years/months and birthdate years/months. */ | |
// You will be blown at how this piece of art works! | |
const CURRENT_YEAR = new Date().getFullYear(); // rightnow: 2019 | |
const CURRENT_MONTH = new Date().getMonth() + 1; // rightnow: 8 (august) | |
const convertAgeBirthdateYearMonths = (month = null, year = null) => { | |
const deltaAmount = (CURRENT_YEAR - year) * 12 + CURRENT_MONTH - month; | |
const convertedMonth = deltaAmount % 12; | |
const convertedYear = (deltaAmount - convertedMonth) / 12; | |
return {convertedMonth, convertedYear}; | |
}; | |
console.log(convertAgeBirthdateYearMonths(2,1)); // 1 year 2 months old => {6, 2018} - Jun 2018 | |
console.log(convertAgeBirthdateYearMonths(6,2018)) // 6/2018 => {1, 2} - 1 year 2 months old | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment