js两时间段相差年份 周岁计算 及 计算按指定日期的周岁计算

/**
 * 当天 周岁计算
 * @param {生日} strBirthday 
 */
export function getAge(strBirthday) {
  let fullAge;
  let strBirthdayArr = strBirthday.split("-");
  let birthYear = strBirthdayArr[0];
  let birthMonth = strBirthdayArr[1];
  let birthDay = strBirthdayArr[2];

  let d = new Date();
  let nowYear = d.getFullYear();
  let nowMonth = d.getMonth() + 1;
  let nowDay = d.getDate();

  if (nowYear == birthYear) {
    fullAge = 0; //同年 则为0岁
  } else {
    let ageDiff = nowYear - birthYear; //年之差
    if (ageDiff > 0) {
      if (nowMonth == birthMonth) {
        let dayDiff = nowDay - birthDay; //日之差
        if (dayDiff < 0) {
          fullAge = ageDiff - 1;
        } else {
          fullAge = ageDiff;
        }
      } else {
        let monthDiff = nowMonth - birthMonth; //月之差
        if (monthDiff < 0) {
          fullAge = ageDiff - 1;
        } else {
          fullAge = ageDiff;
        }
      }
    } else {
      fullAge = -1; //返回-1 表示出生日期输入错误 晚于今天
    }
  }
  return fullAge; //返回周岁年龄
}

/**
 * 次日周岁计算
 */
// next day
export function get_next_day_age(birthday){
  let brithMS = parseInt((new Date(birthday.split('-').join('/'))).getTime());
  return  getAge(date_format(brithMS - 24*60*60, "yyyy-MM-dd"));
}

/ / 和周岁计算函数方法一样 区别在于 周岁 计算 按当天时间  此方法为自定义事件
/**
 * 获取两时间段相差 精确到日 返回 年 <number>
 * @param {*} startTime 
 * @param {*} endTime 
 */
export function getYearSub(startTime, endTime) {
  let fullAge;
  let startTimeArr = startTime.split("-");
  let birthYear = startTimeArr[0];
  let birthMonth = startTimeArr[1];
  let birthDay = startTimeArr[2];

  //ios 时间显示NAN,
  let d = new Date(endTime.replace(/-/g, '/'));
  let nowYear = d.getFullYear();
  let nowMonth = d.getMonth() + 1;
  let nowDay = d.getDate();

  if (nowYear == birthYear) {
    fullAge = 0; //同年 则为0岁
  } else {
    let ageDiff = nowYear - birthYear; //年之差
    if (ageDiff > 0) {
      if (nowMonth == birthMonth) {
        let dayDiff = nowDay - birthDay; //日之差
        if (dayDiff < 0) {
          fullAge = ageDiff - 1;
        } else {
          fullAge = ageDiff;
        }
      } else {
        let monthDiff = nowMonth - birthMonth; //月之差
        if (monthDiff < 0) {
          fullAge = ageDiff - 1;
        } else {
          fullAge = ageDiff;
        }
      }
    } else {
      fullAge = -1;
    }
  }
  return fullAge; //返回周岁年龄
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值