Jump to page content

Dynamic age display

Visitors to my about page will notice that it dynamically generates my age each time you visit. This is not a very difficult thing to do, and here is how:

  1. $dob = mktime(hour, min, sec, month, day, year);

    Generates a UNIX timestamp (the number of seconds since 1st January 1970 00:00 GMT) from your date of birth; all six arguments are numeric. For more information, look up mktime() in the PHP documentation. Bear in mind that the timestamp will be generated with the date and time treated as being in the same timezone as the server, so those with hosting run from a different time zone may wish to take extra measures there. People in the GMT time zone can use the gmmktime() function which treats the arguments as being a time in GMT.

  2. echo round(((time() - $dob) / 31557600), 3);

    This code obtains the current timestamp (in GMT), subtracts your date of birth to get your age in seconds, and divides it by the number of seconds in a year to get your precise age, rounding it to three decimal places. Bear in mind that this will be your age in GMT (because UNIX time works in GMT); again, adjustments will need to apply for those in other timezones wanting a precise age.

I have unfortunately discovered that the result of this code may be up to several hours out. The code assumes 365.25 days per year, which is an approximation and will lead to errors depending on exactly how many leap days have occurred so far in your life. Right now, I do not feel trying to solve this one.

An alternative version is a more human form. Instead of rounding the date and echoing it, store it in $precDate. Then you can do something fun like:

$age = floor($precDate); // get integer age $ageDiff = $precDate - $age; // get fraction of age if ($ageDiff > 0.85) echo "almost ".($age + 1)."years old"; else echo $age."years old";

Further variants on the above are possible using different tests on $ageDiff. Have fun.

Return to the PHP code repository