< BACK CONTINUE >

Date Calculations

The simplest way to work out the length of time between two dates in PHP is to use the difference between UNIX time stamps. We have used this approach in the script shown in Listing 18.1.

Listing 18.1 calc_age.php—Script Works Out a Person's Age Based on His Birthdate
<?
 // set date for calculation
 $day = 18;
 $month = 9;
 $year = 1972;

 // remember you need bday as day month and year
 $bdayunix = mktime ("", "", "", $month, $day, $year); // get unix ts for bday
 $nowunix = time(); // get unix ts for today
 $ageunix = $nowunix - $bdayunix; // work out the difference
 $age = floor($ageunix / (365 * 24 * 60 * 60)); // convert from seconds to
                                                //years

 echo "Age is $age";
?>

In this script, we have set the date for calculating the age. In a real application it is likely that this information might come from an HTML form.

We begin by calling mktime() to work out the time stamp for the birthday and for the current time:

					
$bdayunix = mktime ("", "", "", $month, $day, $year);
$nowunix = mktime(); // get unix ts for today

				

Now that these dates are in the same format, we can simply subtract them:

					
$ageunix = $nowunix - $bdayunix;

				

Now, the slightly tricky part—to convert this time period back to a more human-friendly unit of measure. This is not a time stamp but instead the age of the person measured in seconds. We can convert it back to years by dividing by the number of seconds in a year. We then round it down using the floor() function as a person is not said to be, for example 20, until the end of his twentieth year:

					
$age = floor($ageunix / (365 * 24 * 60 * 60)); // convert from seconds to years

				

Note, however, that this approach is somewhat flawed as it is limited by the range of UNIX time stamps (generally 32-bit integers).

< BACK CONTINUE >

Index terms contained in this section

calculating dates in PHP 2nd
code listings
      script that works out a person
date and time
     in PHP
            date calculations 2nd
            floor() function
            mktime() function
floor() function
functions
      floor()
      mktime()
mktime() function
PHP
     date and time
            date calculations 2nd
            floor() function
            mktime() function
time and date
     in PHP
            date calculations 2nd
            floor() function
            mktime() function

© 2002,Cosmos Inc.