js方法-通过出生日期计算出当前年龄

/**
* 通过出生日期获取当前年龄
* @param strBirthday:指的是出生日期,格式为"1990-01-01",字符串类型
*/
function getCurrentAgeByBirthDate(strBirthday){
    // 将出生日期的字符串通过"-"分割成数组
   	const strBirthdayArr = strBirthday.split("-")
   	// 拿到出生日期的年
    const birthYear = strBirthdayArr[0]
    // 拿到出生日期的月
    const birthMonth = strBirthdayArr[1]
    // 拿到出生日期的日
    const birthDay = strBirthdayArr[2]
    // 创建一个时间对象
   	const d = new Date()
   	// 拿到当前时间的年
    const nowYear = d.getFullYear()
    // 拿到当前时间的月
    const nowMonth = d.getMonth() + 1
    // 拿到当前时间的日
    const nowDay = d.getDate()
    // 如果出生日期的年等于当前时间的年
    if(nowYear === birthYear) return 0 // 返回周岁年龄 0,并终止函数执行
    // 如果如果出生日期的年不等于于当前时间的年,则拿到年之差
    const ageDiff = nowYear - birthYear ; // 年之差
    // 如果年之差是个负数,则表示用户输入的出生日期错误,晚于今天,返回 -1,并终止函数执行
    if(ageDiff < 0) return -1 // 返回错误 -1,并终止函数执行
    // 如果年之差是个正整数,但出生日期的月与当前时间的月不相等
    if(nowMonth !== birthMonth){
    	// 拿到出生日期的日与当前时间的月之差
    	const monthDiff = nowMonth - birthMonth; // 月之差
    	// 如果月之差是个负数,则年之差 - 1后得到周岁年龄,否则直接得到周岁年龄
    	return monthDiff < 0 ? ageDiff - 1 : ageDiff  // 返回周岁年龄,并终止函数执行
    }
    // 如果出生日期的月与当前时间的月相等,则拿到出生日期的日与当前时间的日之差
    const dayDiff = nowDay - birthDay;
    // 如果日之差是个负数,则年之差 - 1得到周岁年龄,否则直接得到周岁年龄
    return dayDiff < 0 ? ageDiff - 1 : ageDiff // 返回周岁年龄,并终止函数执行
}

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值