Determining Date Intervals
Problem
You want to find the time that has elapsed between two dates.
Solution
Convert each date to a timestamp, find their difference, and then convert the difference to human-readable output.
Discussion
For this problem, we need to use the mktime() function, which returns the number of seconds since the UNIX epoch began (January 1, 1970). This is how this problem can be solved with mktime():
<?php $date1 = "11/15/1999"; $date2 = "12/10/2000"; list ($month1, $day1, $year1) = explode ("/", $date1); list ($month2, $day2, $year2) = explode ("/", $date2); $timestamp1 = mktime (0, 0, 0, $month1, $day1, $year1); $timestamp2 = mktime (0, 0, 0, $month2, $day2, $year2); $diff = ($timestamp1 > $timestamp2) ? ($timestamp1 - $timestamp2) : ($timestamp2 - $timestamp1); print "The difference between the dates is "; print date ("Y", $diff) - 1970; print " year(s), " . (date ("m", $diff) - 1); print " month(s) and " . (date ("d", $diff) - 1); print " day(s)."; ?>
Here we split each date into component parts and then create a timestamp for each date. Depending on which timestamp is later, we calculate the difference and then use the date() function to print out the nicely formatted output.