Skip to content

Instantly share code, notes, and snippets.

@locmai0808
Last active August 6, 2019 01:03
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 locmai0808/09616c45ca482ed4156c05193b75bb5a to your computer and use it in GitHub Desktop.
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
/* 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