PHP Subtract Dates

Posted by on in How to
  • Font size: Larger Smaller
  • Subscribe to this entry

The following function will return the number of days between two dates.

function dateDiff($beginDate, $endDate) {
    $fromDate = date('Y-n-j',strtotime($beginDate));
    $toDate = date('Y-n-j',strtotime($endDate));
    $date_parts1=explode('-', $beginDate);
    $date_parts2=explode('-', $endDate);
    $start_date=gregoriantojd($date_parts1[1], $date_parts1[2], $date_parts1[0]);
    $end_date=gregoriantojd($date_parts2[1], $date_parts2[2], $date_parts2[0]);
    return $end_date - $start_date;
}
// example
$from = '2011-1-6';
$to = '2011-1-8';
dateDiff($from,$to); // returns 2
Last modified on
Tagged in: code function PHP
Trackback URL for this blog entry.
Dustin is a web technologist from Wisconsin USA with over 12 yrs. experience consulting entrepreneurs, businesses and local government in web technology. Recently, he's been a bit of a Joomla nut.
  • Guest
    Stephen Sunday, June 26, 2011

    Is it not easier to subtract the timestamps for the two dates and divide by the number of seconds in each day?

  • Admin Dustin
    Dustin Wednesday, July 27, 2011

    Quite possibly. I was experimenting with gregoriantojd which may not be the most efficient. Can you provide an example function with timestamps?

  • Guest
    Stephen Friday, August 26, 2011

    Can you try out the following updates to the subtraction function using the DateTime objects from PHP 5.2 and 5.3. some features are not available in 5.2 so there is an option. However it may need benchmarking for memory usage
    function dateDiff($beginDate, $endDate) {
    $fromDate = new DateTime($beginDate); // works like strtotime
    $toDate = new DateTime($endDate); // works like strtotime

    # > 5.3.0
    $interval = $toDate->diff($fromDate); // difference is a DateInterval object
    return $interval->format(‘%d’) ; // the number of days, requires a % before the format value

    # PHP 5 5.2
    # return intval(($toDate->format(‘U’) – $fromDate->format(‘U’)) / (24 * 3600)); // the diff method in the date and time class is not available so use the timestamps
    }

Leave your comment

Guest Wednesday, July 23, 2014