A simple way to work out the length of time between two dates in PHP is to use the difference between Unix timestamps.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN"> <head> <title>Calculating Dates in PHP</title> <meta Name="Author" Content="Hann So"> </head> <body> <p> <?php if (isset($_POST['submit'])) { process_form(); } else { display_form();// display form for the first time } function display_form() { echo <<<HTML <h2>Calculate the age based on birthdate</h2> <form action = "$_SERVER[SCRIPT_NAME]" method="post"> Month: <input type="text" name="mm" size="50" value="07" /> <br /> Day: <input type="text" name="dd" size="50" value="04" /> <br /> Year: <input type="text" name="yy" size="50" value="1972" /> <br /> <input type="submit" name="submit" value="Submit" /> </form> HTML; } function process_form() { $mm = "$_POST[mm]"; $dd = "$_POST[dd]"; $yy = "$_POST[yy]"; $bday = mktime(0,0,0, $mm, $dd, $yy); $today = time(); $ageunix = $today - $bday; // convert from seconds to year $age = floor($ageunix / (365*24*60*60)); echo "The age is $age<br />"; echo "<p><a href=\"$_SERVER[SCRIPT_NAME]\">Try again?</a></p>\n"; } ?> </p> </body> </html> |