年龄计算

年龄计算得出周岁,不精确算出月日,即只显示几岁
/**
 * 根据生日得到年龄
 * @param {String | Date | Number} [birthday] 生日
 * @returns {Number}
 */
function getAgeByBirth(birthday){
	let age;
	const nowDate = new Date();
	const birthDate = birthday ? new Date(birthday) : new Date();
	const nowY = nowDate.getFullYear();
	const birthY = birthDate.getFullYear();
	const nowM = nowDate.getMonth();
	const birthM = birthDate.getMonth();
	const nowD = nowDate.getDate();
	const birthD = birthDate.getDate();
	if (nowDate.getTime() < birthDate.getTime()) {
		age = 0;
	} else {
		if (nowY == birthY) {
			age = 0;
		} else {
			age = nowY - birthY;
			if (nowM < birthM) {
				age--;
			} else if (nowM == birthM && nowD < birthD) {
				age--;
			}
		}
	}
	return age;
}
计算岁数精确到天

最近遇到需求要计算出不足两岁的得出一岁几月,不足一岁的得出几月几天,不足月的得出几天。由于计算天数涉及到获取前一月份天数,月份天数涉及到是否闰年的2月,以及跨年等情况。计算逻辑复杂,因此借助moment库进行处理。

import moment from 'moment';
/**
 * 根据生日得到年龄
 * @param {Moment|String|Number|Date|Array} [birth] 生日
 * @returns {String}
 */
function getAgeByBirth(brith) {
  if (!brith) return '';
  const duration = moment.duration(moment().diff(brith));
  const years = duration.years();
  const months= duration.months();
  const days= duration.days();
  let result = '';
  if (years > 1) {
    result = years + '岁';
  } else {
    if (years === 1) {
      result = years + '岁' + months + '月';
    } else if (months > 0) {
      result = months + '月' + days + '天';
    } else {
      result = days + '天';
    }
  }
  return result;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值