0

dob format is 2022-07

desired output is 0 Years 5 Months

Below is the code I tried but I am getting months in negative.

export default function calculateAge(date) {
  let month = new Date().getMonth() - Number(date.split("-")[1]);
  let year = new Date().getFullYear() - Number(date.split("-")[0]);
  console.log(`month is`, month);

  if (month < 0 && year < 1) {
    month = year * 12 + month;
    year = 0;
  }

  console.log(`year`, year);

  return `${year ? `${year} Year${year > 1 ? `s` : ""}` : ""} ${
    month ? `${month} Month${month > 1 ? "s" : ""}` : ""
  }`;
}

Chandler Bing
  • 410
  • 5
  • 25
  • I think you should take a look at my answer, (the one you validated is not completely accurate...) https://stackoverflow.com/questions/74645464/calculate-age-from-date-and-month-only-js/74648559#74648559 – Mister Jojo Dec 01 '22 at 23:07
  • One algorithm is to convert each date to months as `year * 12 + month`, get the difference, then convert back using `let [years, months] = [diff / 12 | 0, diff % 12]`. – RobG Dec 02 '22 at 12:05

1 Answers1

0
function calculateAge(date) {
  // Split the date string into year and month
  const [year, month] = date.split("-");

  // Get the current year and month
  const currentYear = new Date().getFullYear();
  const currentMonth = new Date().getMonth() + 1; // months are 0-indexed in JavaScript

  // Calculate the difference in years and months
  let ageYears = currentYear - Number(year);
  let ageMonths = currentMonth - Number(month);

  // If the age in months is negative, subtract 1 from the age in years and add 12 to the age in months
  if (ageMonths < 0) {
    ageYears -= 1;
    ageMonths += 12;
  }

  // Return the age in years and months as a string
  return `${ageYears ? `${ageYears} Year${ageYears > 1 ? `s` : ""}` : ""} ${
    ageMonths ? `${ageMonths} Month${ageMonths > 1 ? "s" : ""}` : ""
  }`;
}
Raz Luvaton
  • 3,166
  • 4
  • 21
  • 36
  • A few examples, particularly of problematic dates, would be good (leap years, start and end near each other, close to end of year, etc.). – RobG Dec 02 '22 at 08:55