【问题标题】:Calculate age from date and month only JSCalculate age from date and month only JS
【发布时间】:2022-12-02 01:05:56
【问题描述】:

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" : ""}` : ""
  }`;
}

【问题讨论】:

    标签: javascript date


    【解决方案1】:
    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" : ""}` : ""
      }`;
    }
    

    【讨论】:

      【解决方案2】:

      function calculateAge(date) {
        const now = new Date()
        const then = new Date(date.split('-'))
      
        const diff = new Date(now - then)
        const months = diff.getMonth()
        const years = diff.getUTCFullYear() - 1970
      
        return `${years} ${years !== 1 ? 'Years' : 'Year'} ${months} ${months !== 1 ? 'Months' : 'Month'}`
      }
      
      const age = calculateAge('2010-05')
      console.log(age)

      【讨论】:

        猜你喜欢
        • 2020-07-21
        • 2022-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-09-24
        • 2011-12-05
        相关资源
        最近更新 更多