开发者

Javascript age calculation on IPad

On every regular b开发者_开发百科rowser, the date is calculated normally .. like 38 year old.

On IPad I get a Not a Number (NaN) error... but why?

function getAge(date) {
    var today = new Date();
    var birthDate = new Date(date);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;

}

EDIT: NaN @ IPad, IE8 and correct working at Firefox&Chrome


You need to do the following transformations on the input date string for it work properly on iPad/iPhone.

function getAge(date) {
    date = date.replace(/-/,"/").replace(/-/,"/"); //substitute - with /
    var today = new Date();
    var birthDate = new Date(date);
    var age = today.getFullYear() - birthDate.getFullYear();
    var m = today.getMonth() - birthDate.getMonth();
    if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
        age--;
    }
    return age;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜