Home >Web Front-end >JS Tutorial >How Can I Accurately Calculate Age from a YYYYMMDD Birthdate?

How Can I Accurately Calculate Age from a YYYYMMDD Birthdate?

DDD
DDDOriginal
2024-12-13 01:28:09215browse

How Can I Accurately Calculate Age from a YYYYMMDD Birthdate?

Calculating Age from YYYYMMDD Formatted Birth Dates

Determining an individual's age based on their birth date in YYYYMMDD format can be achieved with various programming techniques. One approach is to utilize the Date() function.

Consider the following improved solution, which eliminates the use of substrings:

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;
}

To demonstrate the functionality, let's provide an example:

var dob = '19800810';
var age = getAge(dob);

console.log(age); // Output: 41

This improved solution takes advantage of the built-in Date() function, which simplifies the calculation of age while maintaining accuracy.

The above is the detailed content of How Can I Accurately Calculate Age from a YYYYMMDD Birthdate?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn