PHP Difference Between Two Dates

Today, I am going to talk to you about difference of days in two given dates using PHP. There are many methods to get days in PHP, You can use DATETIME() function to get days difference between two dates in PHP.

However, I’ll use a PHP function in this tutorial to convert the date in timetamp , Then subtract startDate from endDate.

You can also check other recommended Date PHP tutorials,

Days Difference Between two dates in PHP

$daysLeft = 0;
$fromDate = "2016-03-15";
$curDate = date('Y-m-d');
$daysLeft = abs(strtotime($curDate) - strtotime($fromDate));
$days = $daysLeft/(60 * 60 * 24);

printf("Days difference between %s and %s = %d", $fromDate, $curDate, $days);

Output : Days difference between 2016-03-15 and 2016-11-30 = 260

I subtract the current date from the previous date and use abs() php method for absolute value. I am using the function strtotime() that will convert date into unix time-stamp that’s why I am getting the difference between two dates in a timestamp.

Finally, I am converting this timestamp into days using the formula (second in a minute*minutes in an hour*hour in a day).

PHP Difference between two dates in Hours

The following code help to get the Hours difference between two dates.

$daysLeft = 0;
$fromDate = "2016-03-15";
$curDate = date('Y-m-d');
$daysLeft = abs(strtotime($curDate) - strtotime($fromDate));
$hour = $daysLeft/(60 * 60);

printf("hours difference between %s and %s = %d", $fromDate, $curDate, $hour);

Output : hours difference between 2016-03-15 and 2016-12-07 = 6408

As you can see, I convert two date differences in hours using PHP. I use the same formula as above except for hours. The formula is (second in a minute*minutes in an hour).

PHP date differences in months, days and year using PHP Datetime()

DateTime class was introduced in PHP 5.2. Its better than old date() and time() functions. Two parameters are required for the DateTime() method:

  • The first is the time value, you can use a date format, unix timestamp, a day interval or a day period.
  • The second parameter is the timezone that you want to assign the date value.

PHP Difference in Months Between two Dates

The following code help to find the Month’s difference between two dates.

$fromDate = new DateTime('2016-03-15');
$curDate = new DateTime();

$months = $curDate->diff($fromDate);
echo $months->format('%m months');

Output : 8 months

Option 2: Finding the Number of Days Between two dates

You can use PHP new DateTime() function to get days difference between two dates.

$datetime1 = new DateTime("2020-06-23");

$datetime2 = new DateTime();

$difference = $datetime1->diff($datetime2);

echo 'Difference: '.$difference->y.' years, ' 
                   .$difference->m.' months, ' 
                   .$difference->d.' days';

The output:
Difference: 1 years, 1 months, 2 days

Leave a Reply

Your email address will not be published. Required fields are marked *