以月为单位计算当前年龄

Calculate current age in months

本文关键字:计算 为单位      更新时间:2023-09-26

我需要以月为单位的年龄,按给定的生日和当前日期:

我找到了这个,它给出了我的年龄:

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    age = age * 12 + m;
    return age;
}

但是我需要以月为单位的年龄。一个五岁的孩子应该得到60分;如果孩子是5岁零3个月大,结果应该是63。

http://jsfiddle.net/n33RJ/567/

实际上,您发布的函数确实返回月数。

复制:

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    age = age * 12 + m;
    return age;
}

我运行getAge('1990-May-16'),结果是305,也就是25年零5个月。

您的jsfiddle使用了一个无效的日期字符串——getAge("10.07.14")

使用年* 12,然后加上月差。如果我们有2011年2月,但孩子出生在2010年4月,你得到1*12+(-2)=10个月

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = (today.getFullYear() - birthDate.getFullYear())*12+(today.getMonth() - birthDate.getMonth());
    return age;
}
function getAge(dateString) {
    var today = new Date();
    var birth = new Date(dateString);
    var years = today.getFullYear() - birth.getFullYear();
    var months = today.getMonth() - birth.getMonth();
    return years * 12 - months;   
}

另一个使用getTime的精度…

function getAge(dateString) {
    var today = new Date();
    var birth = new Date(dateString);
    var timeDiff = today.getTime() - birth.getTime();
    var yearDiff = timeDiff / (24 * 60 * 60 * 1000) / 365.25;
    return yearDiff * 12;
}