Specifications
will return the date formatted as a UNIX time stamp. You can then do as you will with it
in PHP.
As a rule of thumb, use a UNIX timestamp for date calculations and the standard date format
when you are just storing or showing dates. It is simpler to do date calculations and compar-
isons with the UNIX timestamp.
Date Calculations
The simplest way to work out the length of time between two dates in PHP is to use the differ-
ence 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;
Part Title
P
ART IV
398
23 7842 CH18 3/6/01 3:43 PM Page 398










