[JavaScript]YYYY-MM-DD格式字符串计算年龄

function getAge(birth){
	birth = birth.replace(/-/g,"/"); //把格式中的"-"替换为"/"
	birth = new Date(birth ); //替换后转为Date类型
    var now = new Date(); //获取当前日期
    var nowYear=now.getFullYear(); //当前日期的年份
	var nowMonth=now.getMonth();
	var nowDay=now.getDay();

	var birthYear=birth.getFullYear();
	var birthMonth=birth.getMonth();
	var birthDay=birth.getDay(); //出生日期的日数
	var age;
	
	if(birth>now){
		return false;
	}
	else if(nowYear==birthYear||(nowYear>birthYear&&nowMonth>=birthMonth&&nowDay>=birthDay)){
		age=nowYear-birthYear;
		}else {
			age=nowYear-birthYear-1; //简而言之,没过生日岁数不能+1
		}
	return age;
	}

另一种实现方式比较简单:


function getAge(tmpStr){
        var nowdate = new Date();//今天
        var birth = new Date(tmpStr.replace(/-/g,"/"));//默认格式出生日期
        var age = ((nowdate-tmpStr)/1000/60/60/24/365);//计算年龄;
        return age;
}

posted @ 2017-08-02 17:22  六层楼  阅读(672)  评论(0编辑  收藏  举报