美文网首页
根据年月日计算年龄(周岁)

根据年月日计算年龄(周岁)

作者: 奔跑的小孩_79d2 | 来源:发表于2019-05-16 09:39 被阅读0次
    // JS日期系列:根据出生日期 得到周岁年龄
    export function getAge (strBirthday) {
      let returnAge
      const strBirthdayArr = strBirthday.split('-')
      const birthYear = strBirthdayArr[0] * 1
      const birthMonth = strBirthdayArr[1] * 1
      const birthDay = strBirthdayArr[2] * 1
    
      const d = new Date()
      const nowYear = d.getFullYear()
      const nowMonth = d.getMonth() + 1
      const nowDay = d.getDate()
    
      if (nowYear === birthYear) {
        returnAge = 0 // 同年 则为0岁
      } else {
        const ageDiff = nowYear - birthYear // 年之差
        if (ageDiff > 0) {
          if (nowMonth === birthMonth) {
            const dayDiff = nowDay - birthDay // 日之差
            if (dayDiff < 0) {
              returnAge = ageDiff - 1
            } else {
              returnAge = ageDiff
            }
          } else {
            const monthDiff = nowMonth - birthMonth // 月之差
            if (monthDiff < 0) {
              returnAge = ageDiff - 1
            } else {
              returnAge = ageDiff
            }
          }
        } else {
          returnAge = -1 // 返回-1 表示出生日期输入错误 晚于今天
        }
      }
      return returnAge // 返回周岁年龄
    }
    

    相关文章

      网友评论

          本文标题:根据年月日计算年龄(周岁)

          本文链接:https://www.haomeiwen.com/subject/nsrbaqtx.html