How to Get Difference Between Two Dates in PHP

Reading Time: 3 minutes
1,607 Views

Inside this article we will see a basic concept of PHP i.e How to get difference between two dates in PHP. Article contains classified information about getting differences of dates, months, years between two dates in PHP.

We need this concept i.e difference between two dates in days, difference between two dates in months, difference between two dates in years.

Finding difference two dates is necessary when we do any reporting of data along with dates

Learn More –

Let’s get started.


Example 1: Difference Between two Dates in days

Create a file index.php at your localhost directory.

Open index.php and write this complete code into it.

<?php

$startDate = "2021-05-20";
$endDate = "2021-07-27";

$diffData = abs(strtotime($endDate) - strtotime($startDate));

$daysDiff = floor(($diffData - $yearsDiff * 365 * 60 * 60 * 24 - $monthsDiff * 30 * 60 * 60 * 24) / (60 * 60 * 24));

echo " Days: " . $daysDiff;

Output

Days: 68

Example 2: Difference Between two Dates in Months

Create a file index.php at your localhost directory.

Open index.php and write this complete code into it.

<?php

$startDate = "2021-05-20";
$endDate = "2021-07-27";

$diffData = abs(strtotime($endDate) - strtotime($startDate));

$monthsDiff = floor(($diffData - $yearsDiff * 365*60*60*24) / (30*60*60*24));

echo " Months: " . $monthsDiff;

Output

Months: 2

Example 3: Difference Between two Dates in Years

Create a file index.php at your localhost directory.

Open index.php and write this complete code into it.

<?php

$startDate = "2021-05-20";
$endDate = "2023-07-27";

$diffData = abs(strtotime($endDate) - strtotime($startDate));

$yearsDiff = floor($diffData / (365*60*60*24));

echo " Years: " . $yearsDiff;

Output

Years: 2

We hope this article helped you to learn How to Get Difference Between Two Dates in PHP Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.