Klovera.comBlog
Follow Us:

PHP Subtract Dates

Dustin  |  Programming & Scripting  |  January 10th 2011

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

3 Responses to “PHP Subtract Dates”

  1. Stephen says:

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

    • Dustin says:

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

      • Stephen says:

        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 a Reply

Klovera is a forward thinking, full service digital agency whose purpose is to bring value to our client's businesses through creativity, strategy, metrics, user experience and technology.