PHP – Get Different Days Between Two Days

This post will show you how to get difference days between two days in PHP using built-in date_diff function.

The date_diff function is available from PHP version 5.3.0 and above. We will show you code example how to use this function, but before going to that code example part, let’s learn about this function a bit as shown below.

Function/API date_diff($datetime1, $datetime2)
Description Returns difference days between two days.
Parameter Values $datetime1: required and it is DateTime object.
$datetime2: required and it is DateTime object.
Return Values Returns DateInterval object on success or false on failure.


Here is code example that shows how to use date_diff function:

example.php
<?php

// convert string to DateTime object
$datetime1 = date_create_from_format('Y-m-d', '2020-01-01');
$datetime2 = date_create_from_format('Y-m-d', '2020-01-10');

$interval = date_diff($datetime1, $datetime2);
$diffDays = (int) $interval->format('%a');

echo $diffDays; // output: 9

In the code above, before using date_diff, we need to use date_create_from_format function to convert date string to DateTime object.

For reuse, we can move it in a helper function as below:

helpers.php
<?php

// function 1: input are in date string
function getDiffDaysFromDateString($dateStr1, $dateStr2, $dateFormat)
{
	// convert string to DateTime object
	$datetime1 = date_create_from_format($dateFormat, $dateStr1);
	$datetime2 = date_create_from_format($dateFormat, $dateStr2);

	$interval = date_diff($datetime1, $datetime2);
	return (int) $interval->format('%a');
}

echo getDiffDaysFromDateString('2020-01-01', '2020-01-20', 'Y-m-d'); // output: 19


// function 2: input are in DateTime object
function getDiffDaysFromDateTimeObject($datetimeObject1, $datetimeObject2)
{
	$interval = date_diff($datetimeObject1, $datetimeObject2);
	return (int) $interval->format('%a');
}