如何在日期字符串的不同顺序中使年龄计算输出年龄

时间:2014-11-02 15:34:58

标签: javascript datetime

我想计算输入字符串时的用户年龄但是它必须按特定顺序排列,目前这只能按照我想要的日期/月/年的顺序工作,目前它仅适用于月份/日/年

function getAge(dateString) {
    var today = new Date();
    var birthDate = new Date(dateString);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}
console.log('age: ' + getAge("16/01/1972")); **//01/16/1972 works!**

1 个答案:

答案 0 :(得分:1)

试试这个:

function getAge(dateString) {
    var today = new Date();
    var dateData = dateString.split('/');
    var birthDate = new Date(dateData[2], +dateData[1] - 1, dateData[0]);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}
console.log('age: ' + getAge("16/11/1972"));