js根据出生日期计算年龄及根据年龄计算出生日期

1.根据日期算年龄

javascript 复制代码
function mymethod(birthday){
  if(birthday){
    var str = birthday
    birthday=birthday.split('-');
    // 新建日期对象
    let date = new Date()
    // 今天日期,数组,同 birthday
    let today = [date.getFullYear(), date.getMonth() + 1, date.getDate()]
    // 分别计算年月日差值
    let age = today.map((val, index) => {
        return val - birthday[index]
    })
    // 当天数为负数时,月减 1,天数加本月总天数
    if (age[2] < 0) {
        // 获取当月总天数的方法
        let curMonth = new Date(today[0], today[1], 0)
        age[1]--
        age[2] += curMonth.getDate()
    }
    // 当月数为负数时,年减 1,月数加上 12
    if (age[1] < 0) {
        age[0]--
        age[1] += 12
    }
    console.log('出生日期:' + str + "  岁数:" + age[0]+'岁'+age[1]+'月'+age[2]+'天');
  }
}
mymethod('2020-12-06') // 出生日期:2020-12-06  岁数:1岁5月18天

2.根据年龄算日期

ini 复制代码
function myfunction(ageYear,ageMonth,ageDay){//根据年龄算日期
  var subYear = parseInt(ageYear); 
  var subMonth = parseInt(ageMonth); 
  var subDay = parseInt(ageDay); 
  var now = new Date(); 
  var nowYear = now.getFullYear(); 
  var nowMonth = now.getMonth()+1; 
  var nowDay = now.getDate(); // 按照减法原理,先day相减,不够向month借;然后month相减,不够向year借;最后year相减。 
  var day = nowDay - subDay; 
  var month = nowMonth - subMonth; 
  var year = nowYear - subYear; // 检查是否溢出 
  if(day<=0){ // 获得上月的天数 
    var lastMonth = nowMonth - 1; 
    var lastMonthOfYear = nowYear; 
    if(lastMonth<=0){ 
      lastMonth =lastMonth + 12 //(lastMonth + 12) % 12; 
      lastMonthOfYear = lastMonthOfYear - 1;
    } 
    day = day + new Date(lastMonthOfYear, lastMonth, 0).getDate(); 
    month = month - 1; 
  } 
  if(month<=0){ 
    month =month + 12 //(month + 12) % 12; 
    year--; 
  } 
  if(month<10){
    month='0'+month
  }
  if(day<10){
    day='0'+day
  }
  console.log(year+'-'+month+'-'+day);
}
myfunction(1,10,20)

感谢:juejin.cn/post/710112...

相关推荐
OEC小胖胖几秒前
14|Hook 的实现视角:从 API 到 Fiber Update Queue 的连接点
前端·react.js·前端框架·react·开源库
i7i8i9com2 分钟前
React 19学习基础-2 新特性
javascript·学习·react.js
军军君013 分钟前
Three.js基础功能学习十:渲染器与辅助对象
开发语言·前端·javascript·学习·3d·前端框架·ecmascript
Marshmallowc4 分钟前
React useState 数组 push/splice 后页面不刷新?深度解析状态被『蹭』出来的影子更新陷阱
前端·react.js·前端框架
GIS之路8 分钟前
ArcGIS Pro 添加底图的方式
前端·数据库·python·arcgis·信息可视化
Mo_jon9 分钟前
vite + vue 快速构建 html 页面 (舒适编写html文件)
前端·vue.js·html
步步为营DotNet11 分钟前
深度解析.NET 中Nullable<T>:灵活处理可能为空值的类型
java·前端·.net
VT.馒头13 分钟前
【力扣】2631. 分组
javascript·算法·leetcode·typescript
许同23 分钟前
JS-WPS 自动化办公(3)数据整理-找数据
开发语言·javascript·wps
rqtz27 分钟前
前端相关动画库(GSAP/Lottie/Swiper/AOS)
前端·swiper·lottie·gsap·aos·font-awsome