通过生日计算年龄

// 获取当前月
function getDate(date) {
  let d = new Date(date);
  // 将日期设置为下月一号
  d.setMonth(d.getMonth() + 1);
  d.setDate('1');
  // 获取本月最后一天
  d.setDate(d.getDate() - 1);
  return d.getDate();
}
// 获取年龄 传出生日期和当前日期,当前日期可以不用传
function getAge(birthday = '', lastDay = "") {
  // 没有传生日不计算
  if (!birthday) return
  // 先截取到字符串中的年、月、日
  let selectYear = birthday.split('-')[0]
  let selectMonth = birthday.split('-')[1]
  let selectDay = birthday.split('-')[2]
  // 得到当前时间的年、月、日
  let cal = lastDay === '' ? new Date() : new Date(lastDay);
  let yearNow = cal.getFullYear();
  let monthNow = cal.getMonth() + 1;
  let dayNow = cal.getDate();

  // 用当前年月日减去生日年月日
  let yearMinus = yearNow - selectYear;
  let monthMinus = monthNow - selectMonth;
  let dayMinus = dayNow - selectDay;

  let age = '';
  if (yearMinus < 0) {
    return "生日不可小于当前时间"
  } else {
    if (yearMinus === 0) {
      if (monthMinus < 0) {
        return '生日不可小于当前时间'
      } else {
        if (monthMinus > 0) {
          if (dayMinus >= 0) {
            return monthMinus + '个月' + (dayMinus > 0 ? dayMinus + '天' : '')
          }
          return ((monthMinus - 1) === 0 ? '' : (monthMinus - 1) + '个月') + (dayNow + (getDate(birthday) - selectDay)) + '天'
        } else {
          if (dayMinus < 0) {
            return '生日不可小于当前时间'
          }
          return dayMinus + '天'
        }
      }
    } else {
      age = yearMinus + '岁'
      if (monthMinus === 0) {
        if (dayMinus >= 0) {
          return age + (dayMinus === 0 ? '' : dayMinus + '天')
        }
        return (yearMinus - 1 === 0 ? '' : yearMinus - 1 + '岁') + '11个月'
      } else if (monthMinus > 0) {
        age += (dayMinus >= 0 ? monthMinus + '个月' : (monthMinus - 1 > 0 ? monthMinus + '个月' : (getDate(birthday) - selectDay + dayNow + '天')))
        return age;
      } else {
        return (yearMinus - 1 === 0 ? '' : yearMinus - 1 + '岁') + (12 - selectMonth + monthNow) + '个月'
      }
    }
  }
}

console.log(getAge('2001-07-04'))

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

巨蟹座守护骑士

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值