js把日期时间转换为生日周岁月

例如出生 10个月  2岁

   getDate(date) {
        let d = new Date(date);
        return new Date(d.getFullYear(), d.getMonth()+1, 0).getDate();
    },
     getAge(birthday, lastDay=this.$moment(new Date()).format('YYYY-MM-DD')) {
      //this.$moment(new Date()).format('YYYY-MM-DD')) 这段作用就是默认获取当前日期时间转换为YYYY-MM-DD的格式,这个方法有很多 就没写了
      // console.log(birthday,lastDay);
        // 先截取到字符串中的年、月、日
        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 + '个月'
                        }
                        if((monthMinus - 1) === 0){
                          return   (dayNow + (this.getDate(birthday) - selectDay)) + '天'
                        }else{
                         return (monthMinus - 1) + '个月'
                        }
                    } else {
                        if (dayMinus < 0) {
                            return '生日不可小于当前时间'
                        }
                        return dayMinus + '天'
                    }
                }
            } else {
                age = yearMinus + '岁'
                if (monthMinus === 0) {
                    if (dayMinus >= 0) {
                        return age 
                    }
                    if(yearMinus - 1 === 0){
                      return '11个月'
                    }else{
                      return  yearMinus - 1 + '岁'
                    }
                } else if (monthMinus > 0) {
                    return age;
                } else {
                    if(yearMinus - 1 === 0){
                     return  (12 - selectMonth + monthNow) + '个月'
                    }else{
                     return yearMinus - 1 + '岁'
                    }
                }
            }
        }
    },

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值