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
Why Does a Regexp With Global Flag Give Wrong Results
Loop Through an Array in JavaScript
Firebase Query If Child of Child Contains a Value
How to Use a Variable in a Regular Expression
Is There a JavaScript/Jquery Dom Change Listener
Simplest Code For Array Intersection in JavaScript
How to Set/Unset a Cookie With Jquery
Error: Can't Set Headers After They Are Sent to the Client
Uncaught Referenceerror: $ Is Not Defined
How to Remove All Duplicates from an Array of Objects
How to Access the Matched Groups in a JavaScript Regular Expression
Web-Scraping JavaScript Page With Python
Add a Property to a JavaScript Object Using a Variable as the Name
How to Access the Contents of an Iframe With JavaScript/Jquery