Calculating age from Date of Birth
This has baffled me for years but a couple of nights ago I finally cracked it. How to accurately work out someones Age from their DOB. For this tutorial I’m using the english method of presenting dates DD-MM-YYYY rather than the american way.It actually rather simple by comparing the date of birth to the current date you can not only work out their age but also whether it’s their birthday or not.
First we need to collect the date of birth, I imagine most of you store it the same way as me, in a format like this 00-00-0000 so we first need to split this up. We are going to be using the date the 05-08-1994 as an example, to split this up we will be using the php explode function.
1
2
3
| $dob = "05-08-1994";list($day, $month, $year) = explode("-", $dob);?> |
1
2
3
4
| $curday = date("d");$curmonth = date("m");$curyear = date("Y")?> |
PHP’s date function allows us to calculate pretty much any information you need from days and months to the time accurate to a second. For more information on this you can visit php.net’s date function page.
Now we’ve got all the individual pieces of information we can start to calculate the age. First of all we’re going to find out what the age is roughly. We can do this by taking their birth year from the current year.
1
2
3
| $age = $curyear - $year;$age--;?> |
Now we’ve got this value we’re going to work out if their birthday has already been and if so do we need to add another year to their age.
1
2
3
4
| if ( $curmonth > $month || $curmonth == $month && $curday >= $day) {$age++;}?> |
Now we’ve worked out there age were going to display our result with a simple echo.
1
2
3
| <?phpecho $age;?> |
As I said earlier you can also work out if it’s their birthday and send them a birthday greeting. You can do this by changing the greater than sign in the final part of the if function to an equals sign. Like so.
1
2
3
4
5
| <?phpif ( $curmonth == $month && $curday == $day ) {echo 'happy birthday!';}?/> |
The full source code is below.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
| <?php$dob = "05-08-1994"; list($day, $month, $year) = explode("-", $dob); $curday = date("d"); $curmonth = date("m"); $curyear = date("Y"); $age = $curyear - $year; $age--; if ( $curmonth > $month || $curmonth == $month && $curday >= $day ) { $age++; } if ( $curmonth == $month && $curday == $day ) { echo 'happy birthday!'; }echo $age;?> |
No comments:
Post a Comment