Hi FE !
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
Ai
git
前端面试题
前端小tip
  • vite
  • webpack
npm
  • vue2
  • vue3
react
GitHub
  • 根据出生日期算岁数

根据出生日期算岁数

function myAge(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]+'天');
  }
}
myAge('2022-03-31') // 出生日期:2022-03-31  岁数:2岁4月18天

根据年龄算日期

function myBirth(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);
}
myBirth(1,10,20)

Edit this page
最近更新: 2025/6/27 02:24
Contributors: qdleader
qdleader
本站总访问量 129823次 | 本站访客数 12人