The rewritten title is: Calculate age based on date of birth in YYYYMMDD format
P粉265724930
P粉265724930 2023-08-20 16:03:39
0
2
387
<p>How to calculate age based on date of birth in YYYYMMDD format? Is it possible to use the <code>Date()</code> function? </p> <p>I'm looking for a better solution than what I'm using now: </p> <p><br /></p> <pre class="brush:js;toolbar:false;">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);</pre> <p><br /></p>
P粉265724930
P粉265724930

reply all(2)
P粉574268989

try it.

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 part of your code that looks rough is the substr part.

Fiddlehttp://jsfiddle.net/codeandcloud/n33RJ/

P粉478188786

I would choose readability:

function _calculateAge(birthday) { // birthday is a date
    var ageDifMs = Date.now() - birthday.getTime();
    var ageDate = new Date(ageDifMs); // miliseconds from epoch
    return Math.abs(ageDate.getUTCFullYear() - 1970);
}

Disclaimer: This method also has accuracy issues, so it cannot be completely trusted. Errors may occur in certain years, certain hours, or daylight saving time (depending on time zone).

If accuracy is very important, I recommend using a library to handle this. Also, @Naveens post is probably the most accurate since it is not time dependent.


Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template