Home >Web Front-end >JS Tutorial >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!