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...

相关推荐
炫饭第一名1 天前
Cursor 一年深度开发实践:前端开发的效率革命🚀
前端·程序员·ai编程
摇滚侠1 天前
Vue 项目实战《尚医通》,获取挂号医生的信息展示,笔记43
前端·javascript·vue.js·笔记·html5
晴殇i1 天前
关于前端基础快速跨入鸿蒙HarmonyOS开发
前端·harmonyos
k09331 天前
vue3中基于AntDesign的Form嵌套表单的校验
前端·javascript·vue.js
茶憶1 天前
UniApp RenderJS中集成 Leaflet地图,突破APP跨端开发限制
javascript·vue.js·uni-app
没头脑和不高兴y1 天前
Element-Plus-X:基于Vue 3的AI交互组件库
前端·javascript
ErMao1 天前
Proxy 与 Reflect:最硬核、最实用的解释
前端·javascript
N***73851 天前
前端路由权限动态更新,Vue与React实现
前端·vue.js·react.js
k09331 天前
在组件外(.js文件)中使用pinia的方法2--在http.js中使用pinia
开发语言·javascript·http
xiaoxue..1 天前
用 Node.js 手动搭建 HTTP 服务器:从零开始的 Web 开发之旅!
服务器·前端·http·node.js