计算年龄
返回距离出生x年y月z日
function getAge(birthday) {
var now = new Date();
var birth = new Date(birthday);
//还没有出生
if (now - birth < 0) {
return -1;
}
//获取当前月份天数 下个月的第零天就是这个月份的最后一天
var days = new Date(now.getFullYear(), now.getMonth() + 1, 0).getDate();
var yearDiff = now.getFullYear() - birth.getFullYear();
var monthDiff = now.getMonth() - birth.getMonth();
var dateDiff = now.getDate() - birth.getDate();
//不足一月退位
if (dateDiff < 0) {
dateDiff = days + dateDiff;
monthDiff--;
}
//不足一年退位
if (monthDiff < 0) {
monthDiff = 12 + monthDiff;
yearDiff--;
}
return ({ year: yearDiff, month: monthDiff, date: dateDiff });
}
getAge('1994-12-25');//{year: 22, month: 7, date: 29}即出生已经22年7个月零29天了,即22周岁
网友评论