Calculate Age Given the Birth Date in the Format Yyyymmdd

Calculate age given the birth date in the format yyyy-mm-dd

In php you can do this using the datetime object:

$dateOfBirth = new DateTime($post->date_of_birth);
$today = new DateTime();
$diff = $today->diff($dateOfBirth);
//echo $diff->format("%Y Years, %M Months");

Then if you want to output that as json you can just:

echo json_encode(['diffString' => $diff->format("%Y Years, %M Months")]);

Calculate age given the birth date in the format YYYYMMDD

I would go for 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 also has precision issues, so this cannot be completely trusted either. It can be off by a few hours, on some years, or during daylight saving (depending on timezone).

Instead I would recommend using a library for this, if precision is very important. Also @Naveens post, is probably the most accurate, as it doesn't rely on the time of day.



Calculate age given the birth date in the format YYYYMMDD

I would go for 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 also has precision issues, so this cannot be completely trusted either. It can be off by a few hours, on some years, or during daylight saving (depending on timezone).

Instead I would recommend using a library for this, if precision is very important. Also @Naveens post, is probably the most accurate, as it doesn't rely on the time of day.



How do I calculate someone's age based on a DateTime type birthday?

An easy to understand and simple solution.

// Save today's date.
var today = DateTime.Today;

// Calculate the age.
var age = today.Year - birthdate.Year;

// Go back to the year in which the person was born in case of a leap year
if (birthdate.Date > today.AddYears(-age)) age--;

However, this assumes you are looking for the western idea of the age and not using East Asian reckoning.



Related Topics



Leave a reply



Submit