[JavaScript] 現在幾歲年齡算法

 


   const todayDate = getTodayDate();

   function getTodayDate() {
      const fullDate = new Date();
      const yyyy = fullDate.getFullYear();
      const MM =
        fullDate.getMonth() + 1 >= 10
          ? fullDate.getMonth() + 1
          : '0' + (fullDate.getMonth() + 1);
      const dd =
        fullDate.getDate() < 10 ? '0' + fullDate.getDate() : fullDate.getDate();
      const today = String(yyyy+ String(MM+ String(dd);
      return today;
    }

輸入值為西元年月日共8碼

     let ageGap: number;

        const todayYYYY = Number(todayDate.slice(0, 4));
        const todayMM = Number(todayDate.slice(4, 6));
        const todayDD = Number(todayDate.slice(6, 8));

        const birthYYYY = Number(birthDay.slice(0, 4));
        const birthMM = Number(birthDay.slice(4, 6));
        const birthDD = Number(birthDay.slice(6, 8));

        let calcYYYY: number;
        let calcMM: number;
        let calcDD: number;

        calcYYYY = todayYYYY - birthYYYY;
        calcMM = todayMM - birthMM;

        if (calcMM < 1{
          if (calcMM < 0{
            calcYYYY -= 1;
          } else {
            calcDD = todayDD - birthDD;
            if (calcDD < 0{
              calcYYYY -= 1;
            }
          }
        }
        ageGap = Number(calcYYYY);



















留言

這個網誌中的熱門文章

[Angular] 閒置登出作法

[Angular Materail] 檔案上傳範例

[Angular Material] 搜尋式下拉選單範例