js通过出生日期获取年龄

js通过出生日期跟当前日期对比获取年龄,代码如下,处理不完善处请见谅,谢谢~~~

 /**
  * @uses 根据生日计算年龄,年龄的格式是:2016-09-23
  * @param string birthday
  * @return string|number
  **/
 function getAge(birthday) {
   let iage = 0;
   if (!$.isNull(birthday)) {
     //获取出生日期的年月日
     let year = this.getYmd(birthday,'y');
     let month = this.getYmd(birthday, 'm');
     let day = this.getYmd(birthday, 'd');

  //获取当前时间的年月日
     let myDate = new Date();
     let now_year = myDate.getFullYear(); 
     let now_month = myDate.getMonth()+1; 
     let now_day = myDate.getDate(); 

     if (now_year > year) {
       iage = now_year - year - 1;
       if (now_month > month) {
         iage++;
       } else if (now_month == month) {
         if (now_day >= day) {
           iage++;
         }
       }
     }
   }
   return iage;
 },
 
 /**
  * @uses 根据指定日期返回你年月日,日期格式是:2016-09-23
  * @param string s 日期字符串
  * @param string type 返回的 年y 月m 日d
  * @return string|number
  **/
 function getYmd(s,type) {
   // var s = "2010-5-6";
   let a = s.split("-");
   if (a.length > 2) {
     let y = a[0];
     let m = a[1];
     let d = a[2];
     console.log('y:'+y,'m:'+m,'d:'+d)
     let returnStr = '';
     switch(type){
       case 'y':
         returnStr = y;
         break;
       case 'm':
         returnStr = m;
         break;
       case 'd':
         returnStr = d;
         break;
       default:
         returnStr = '';
         break;
     }
     return returnStr;
   }else{
     return '';
   }
 }
  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

喵喵喵~~~

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

¥2 ¥4 ¥6 ¥10 ¥20
输入1-500的整数
余额支付 (余额:-- )
扫码支付
扫码支付:¥2
获取中
扫码支付

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

打赏作者

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

抵扣说明:

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

余额充值