How to Get Number of Days Between Two Dates in PHP

How to Get Number of Days Between Two Dates in PHP

Sometimes we need to calculate the days between two given dates. In this post, we will see How to Get Number of Days Between Two Dates in PHP with an example. So there are two ways to do the same, one is using the PHP date_diff() and another is using strtotime() function.

We encountered many times in a project when we struggle to manipulate the result around dates. When we know the exact PHP function to get the work done the task becomes very easy but when we have to make our own function to manipulate the output of the date as per need then it becomes a little bit complex task to do. In this article, we are trying to explain How to Get Number of Days Between Two Dates in PHP with the help of two approaches, first with PHP inbuilt function and second with the help of customized function.

For more about PHP date and time queries you can check PHP Date and Time formats

Let’s start and check how we can get number of days between two dates.


Using date_diff() Function:

date_diff() function is an inbuilt PHP function and basically used to calculate the difference between two dates.

 $date1 = date_create("2020-10-01");
 $date2 = date_create("2019-06-18");
 //difference between two dates
 $diff = date_diff($date1,$date2);
 //count days
 echo 'Total Days Count - '.$diff->format("%a");


Total Days Count - 471

We have used two PHP function in the above script to get the number of days between two dates.

date_create() – This function returns a new DateTime object.
date_diff() – This function returns the difference between two DateTime objects.

Example 2

In this example, we are taking two dates and converting them into Unix timestamp (the number of seconds since January 1 1970 00:00:00 GMT). Then take the difference between these two dates and dividing them by the number of seconds in a day. And then using the abs() function we take the absolute value (positive value) of the number of final days. Below is the implementation of this method.


function dateDiffInDays($date1, $date2) 
	// Calculating the difference in timestamps 
	$diff = strtotime($date2) - strtotime($date1); 
	// 1 day = 24 hours 
	// 24 * 60 * 60 = 86400 seconds 
	return abs(round($diff / 86400)); 

// Start date 
$date1 = "17-10-2020"; 

// End date 
$date2 = "01-02-2020"; 

// Function call to find date difference 
$dateDiff = dateDiffInDays($date1, $date2); 
// Display the result 
printf("Difference between two dates: "
. $dateDiff . " Days "); 


Difference between two dates: 259 Days


I the above script we have tried to explain how we can get the number of days between two days. Hope you like the post, if you have any queries, please comment below we would love to help you.

You can also check How to open the numeric keyboard in mobile and validate the length

Spread the love