Compare Dates in PHP – The Utimate Guide

Comparing Dates in PHP – Code Snippet

Here’s a featured snippet from the article that uses DateTime objects for comparing two dates in PHP.

$today = new DateTime("2022-9-6");
$yesterday = new DateTime("2022-9-5");

if($today > $yesterday) echo $today->format("Y-m-d").' is ahead of '.$yesterday->format("Y-m-d");

else echo $today->format("Y-m-d").' is behind '.$yesterday->format("Y-m-d");

//Output
//2022-9-6 is ahead of 2022-9-5

That’s not the only option as the article covers many different options for PHP date comparison. Stay tuned till the end to learn more.

PHP DateTime for Comparing Two Different Dates in PHP

The DateTime class includes many methods that help work with dates and times. This article contains sections on the object-oriented approach for comparison of dates in PHP, where the examples initialize DateTime objects and call instance methods. To have a solid foundation for using the DateTime class, consider reading PHP DateTime

Can we compare two dates in PHP?

PHP features many different functions that focus on dates and times. So, there are different ways to compare dates in PHP. To keep the content organized, the article groups the different ways into two broad sections.

  • Procedural approach of date comparison in PHP.
  • Object-Oriented approach of date comparison in PHP

So, let’s start without any further ado.

Procedural Approach to Comparing Dates in PHP

This approach won’t involve directly working with classes and objects. The examples would use many PHP functions and shy away from OOP patterns.

Compare Dates in PHP using Comparison Operators

Let’s start from the baseline. The string-based dates here have a similar format. Comparison operators would be helpful here.

$today = "2022-9-6";
$yesterday = "2022-9-5";
 
if($today > $yesterday) echo "{$today} is ahead of {$yesterday}";
 
else echo "{$today} is behind {$yesterday}";
 
//Output
//2022-9-6 is ahead of 2022-9-5

This example works just fine. Let’s see another way of determining dates difference.

Compare Dates with strtotime() in PHP

An alternative to working with string dates is calculating the timestamp through strtotime(). The timestamp calculates a timestamp from a given date. The timestamp is an offset from the current time. Let’s see that in action.

$today = "2022-9-6";
$yesterday = "2022-9-5";

$firsttimestamp = strtotime($today);
$secondtimestamp = strtotime($yesterday);

if($firsttimestamp > $secondtimestamp) echo "{$today} is ahead of {$yesterday}";

else echo "{$today} is behind {$yesterday}";

//Output
//2022-9-6 is ahead of 2022-9-5

Option3 – Comparing two Dates in PHP using date_create()

The date_create() is a procedural version of the DateTime constructor. It returns a DateTime object. Many relevant functions expect this object as an argument. The example below uses comparison operators.

$today = date_create("6-9-2022");
$yesterday = date_create("2022-9-5");
 
if($today > $yesterday) echo "6-9-2022 is ahead of 2022-9-5";
 
else echo "6-9-2022 is behind 2022-9-5";
 
//Output
//6-9-2022 is ahead of 2022-9-5

The output is correct despite the different date formats. A downside is that we can’t directly use the objects in a string literal. But there’s a way out, as we explore in the following example.

$today = date_create("6-9-2022");
$yesterday = date_create("2022-9-5");
 
if($today > $yesterday) echo date_format($today, 'Y-m-d'). ' is ahead of '.date_format($yesterday, 'Y-m-d');
 
else echo date_format($today, 'Y-m-d'). ' is behind '.date_format($yesterday, 'Y-m-d');
 
//Output
//2022-09-06 is ahead of 2022-09-05

Voila! Using the date_format() with the right format string, the example resolves the dates to string conversion and also unifies the formatting of the two different dates.

Compare two Dates in PHP using DateInterval

The date_diff() returns the difference between two dates. The function returns the interval. The following example passes the interval to date_interval_format(), returning a string value. This method accepts a bunch of characters to format the interval. Let’s check out an example.

$today = date_create("6-9-2022");
$yesterday = date_create("2022-9-5");

$difference = date_diff($yesterday, $today);

echo date_interval_format($difference, "%d day(s)")." is ahead of ". date_format($yesterday, "Y-m-d");

//Output
//1 day(s) is ahead of 2022-09-05

Awesome! The example returns the difference Compare Dates in terms of intervals in PHP. 

Now is the time to move on to the object-oriented approach. 

Object-Oriented Approach to Comparing Different Dates in PHP

This approach involves the DateTime class, making working with dates and times easier. Let’s not wait and see the different options to compare dates in PHP.

Compare two Dates in PHP using DateTime Objects

The example initializes two different DateTime objects and uses comparison operators and format method to print the dates to the console.

$today = new DateTime("2022-9-6");
$yesterday = new DateTime("2022-9-5");

if($today > $yesterday) echo $today->format("Y-m-d").' is ahead of '.$yesterday->format("Y-m-d");

else echo $today->format("Y-m-d").' is behind '.$yesterday->format("Y-m-d");

//Output
//2022-9-6 is ahead of 2022-9-5

Perfect! DateTime comes with a method that returns an interval. The next example uses the difference in two date intervals in PHP.

How to Compare two Dates in PHP using diff()

Let’s calculate the interval using diff() and return a custom console message.

$today = new DateTime("2022-9-6");
$yesterday = new DateTime("2022-9-5");

echo $today->diff($yesterday)->format('%d day(s)')." ahead of ".$yesterday->format("Y-m-d");

//Output
//1 day(s) ahead of 2022-09-05

Cool! You can pass in other format characters to get the difference in minutes or even seconds.

Phew! That was a long list of different options for PHP date comparison. Let’s wrap up the article.

Conclusion

Wrap Up

This article demonstrates how to compare dates in PHP. The article starts with a procedural approach to calculating the difference between two dates, followed by the object-oriented approach. Apart from that, the example also uses the difference in two date intervals in PHP.

Hopefully, you’ve liked the article. Stay tuned for more at FuelingPHP.

Classes and Functions Mentioned

DateTime: (PHP 5 >= 5.2.0, PHP 7, PHP 8) The DateTime class in PHP represents dates/times and features many useful functions to easily manipulate the objects. It was included in PHP 5.2.0 and remained in use. Given its utility and stability, depreciation seems unlikely.

strtotime: (PHP 4, PHP 5, PHP 7, PHP 8) This core PHP function converts a valid string date to timestamps. This function remains a part of the core PHP library from the 4th installation. It is apparently stable enough to persist in the future.

date_create: (PHP 5 >= 5.2.0, PHP 7, PHP 8) This function is a procedural variant of DateTime constructor function and returns a DateTime object. 

date_diff: (PHP 5 >= 5.3.0, PHP 7, PHP 8) This function is an alias of DateTime’s diff method.

date_interval_format: (PHP 5 >= 5.3.0, PHP 7, PHP 8) An alias of DateTime’s format method.

Want to learn more about PHP?

We have many fun articles related to PHP. You can explore these to learn more about PHP.

  Was this information helpful?

Can Your Career Use a Boost?

Check out our free PHP developer career guide. We created this guide as a resource to help fellow programmers level up their careers. This is an excellent resource whether you are new to programming or have been a professional for more than 15 years.

Click here to read the guide


Article Categories

Article Tags

© 2022 Confident.Systems