Home  >  Q&A  >  body text

The rewritten title is: Calculate age based on date of birth in YYYYMMDD format

<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粉265724930P粉265724930403 days ago337

reply all(2)I'll reply

  • P粉574268989

    P粉5742689892023-08-21 15:03:33

    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/

    reply
    0
  • P粉478188786

    P粉4781887862023-08-21 11:57:16

    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.


    reply
    0
  • Cancelreply