How to compare Dates in PHP?

How to compare Dates in PHP?

In the old days of PHP, we used to compare dates using strtotime(). Since, strtotime converts the given date to the Unix Timestamp i.e. Number of seconds from the epoch, we can then do the basic maths like add, diff, compare with the integers (no of seconds) and then can convert back the unix timestamp to date using date function. e.g.

The Old way. (using strtotime)

Compare Dates
 $startDate) {
    // Do your work here
    echo "End Date is valid and bigger than Start Date";
} else {
    echo "End Date is less than Start Date";
}

?>
How to Subtract Dates in PHP?

But that’s all Old fashioned and have few limitations. Since strtotime returns number of seconds from epoch in Integer and we know that Integers have a limit. As per PHP documentation, The valid range of a timestamp is typically from Fri, 13 Dec 1901 20:45:54 UTC to Tue, 19 Jan 2038 03:14:07 UTC. (These are the dates that correspond to the minimum and maximum values for a 32-bit signed integer.)

So, let’s have a look at the new way:

The New Way or rather better (Using PHP’s DateTime class)

Note: As per PHP documentation, We need PHP >= 5.3.0 to use DateTime class.

So, Now let’s have a look at How to compare dates using PHP’s DateTime?

  $datetime2);
var_dump($datetime1 <  $datetime2);

// And here is the Output
bool(false)
bool(false)
bool(true)

?>

How to calculate the difference between two dates using PHP?

We will use DateTime Class diff method that return the DateInterval. Read more about DateInterval, here.

diff($datetime2);

// Difference in Number of Years
echo $dateInterval->y ."\n";

// Difference in Number of Months
echo $dateInterval->m ."\n";

// Difference in Number of Days
echo $dateInterval->d ."\n";

// Difference in Number of Hours
echo $dateInterval->h ."\n";

// Difference in Number of Minutes
echo $dateInterval->i ."\n";

// Difference in Number of Seconds
echo $dateInterval->s ."\n";

// Difference in Total No of Days
// As per PHP documentation, If the DateInterval object was created by DateTime::diff(), 
// then this is the total number of days between the start and end dates. 
// Otherwise, days will be FALSE
echo $dateInterval->days. "\n";

// Difference in Pretty format
echo $interval->format('%R%a days');

// And here is the Output
0
2
10
20
54
0
69
+69 days

?>

So that’s about Comparing Dates in PHP, Hope you like it.
We will talk about “Dates in PHP” in general in further posts. Till than stay tuned and Happy Coding !!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.