- Using Text Within date()
- Automatically Localizing Dates
- Manually Localizing Dates
- Using the Current Date the U.S./U.K./European Way
- Formatting a Specific Date
- Validating a Date
- Calculating a Relative Date
- Creating a Sortable Time Stamp
- Converting a String into a Date
- Determining Sunrise and Sunset
- Using Date and Time for Benchmarks
- Using Form Fields for Date Selection
- Create Self-updating Form Fields for Date Selection
- Calculating the Difference Between Two Dates
- Using GMT Date/Time Information
Calculating the Difference Between Two Dates
$century = mktime(12, 0, 0, 1, 1, 2001); $today = time(); $difference = $today - $century;
The epoche value that can be determined by time() and other PHP functions can be used to easily calculate the difference between two dates. The trick is to convert the dates into time stamps (if not already available in this format). Then the difference between these two time stamps is calculated. The result is the time difference in seconds. This value can then be used to find out how many minutes, hours, and days this corresponds to:
Divide the result by 60 to get the number of minutes
Divide the result by 60 * 60 = 3600 to get the number of hours
Divide the result by 60 * 60 * 24 = 86400 to get the number of days
<?php $century = mktime(12, 0, 0, 1, 1, 2001); $today = time(); $difference = $today - $century; echo ‘This century started ‘; echo floor($difference / 84600); $difference -= 84600 * floor($difference / 84600); echo ‘ days, ‘; echo floor($difference / 3600); $difference -= 3600 * floor($difference / 3600); echo ‘ hours, ‘; echo floor($difference / 60); $difference -= 60 * floor($difference / 60); echo " minutes, and $difference seconds ago."; ?>
The Difference Between Two Dates (timediff.php)
Figure 3.5 The PHP code filled the month selection list with the appropriate number of days.
If you start with the number of days, round down each result and substract this from the result; you can also split up the difference into days, hours, and minutes.