Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

How can I calculate an age in years, given a birth date of format YYYYMMDD?(给定出生日期格式为YYYYMMDD,我如何计算以岁为单位的年龄?)

Is it possible using the Date() function?(是否可以使用Date()函数?) I am looking for a better solution than the one I am using now:(我正在寻找比现在使用的解决方案更好的解决方案:) var dob = '19800810'; var year = Number(dob.substr(0, 4)); var month = Number(dob.substr(4, 2)) - 1; var day = Number(dob.substr(6, 2)); var today = new Date(); var age = today.getFullYear() - year; if (today.getMonth() < month || (today.getMonth() == month && today.getDate() < day)) { age--; } alert(age);   ask by Francisc translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
407 views
Welcome To Ask or Share your Answers For Others

1 Answer

Try this.(尝试这个。)

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; } I believe the only thing that looked crude on your code was the substr part.(我相信在您的代码上看起来很粗糙的唯一东西是substr部分。) Fiddle : http://jsfiddle.net/codeandcloud/n33RJ/(小提琴http : //jsfiddle.net/codeandcloud/n33RJ/)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...