JS(TS)计算年龄(精确到天数)(也可以将时间转换成moment格式,使用diff方法直接计算,两行代码就搞定了)

博客围绕前端开发,涉及JavaScript(JS)和TypeScript(TS)相关内容,但具体内容未给出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  const onSelectDateChange = (e: any) => {
    const now = new Date();
    let year = now.getFullYear();
    let month = now.getMonth() + 1;
    const day = now.getDate();

    const myDate = new Date(e);
    const myYear = myDate.getFullYear();
    const myMonth = myDate.getMonth() + 1;
    const myDay = myDate.getDate();

    let gapDay = day - myDay;
    if (gapDay < 0) {
      month -= 1;
      gapDay = getDaysOfMonth(e) - myDay + day;
    }
    let gapMonth = month - myMonth;
    if (gapMonth < 0) {
      year -= 1;
      gapMonth = 12 - myMonth + month;
    }
    let gapYear = year - myYear;
    if (gapYear < 0) {
      gapYear = 0;
    }
    if (gapYear === 0) {
      if (gapMonth === 0) {
        const age = `${gapDay}`;
        form.setFieldsValue({
          age,
        });
      } else {
        const age = `${gapMonth}`;
        form.setFieldsValue({
          age,
        });
      }
    } else {
      const age = `${gapYear}`;
      form.setFieldsValue({
        age,
      });
    }
  };

  // 获取当月的天数
  const getDaysOfMonth = (age: any) => {
    const date = new Date(age);
    const year = date.getFullYear();
    const mouth = date.getMonth() + 1;
    let day = 0;
    if (mouth === 2) {
      day = isLeapYear(year) ? 29 : 28;
    } else if (
      mouth === 1 ||
      mouth === 3 ||
      mouth === 5 ||
      mouth === 7 ||
      mouth === 8 ||
      mouth === 10 ||
      mouth === 12
    ) {
      day = 31;
    } else {
      day = 30;
    }
    return day;
  };
  // 判断是否为闰年
  const isLeapYear = (year: any) => {
    return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  };

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值