Compare date with date list in PHP

Compare date with date list in PHP

October 19, 2026 · Illustrated author avatarBy Stefan Bogdanescu
Compare date with date list in PHP

Comparing Date Lists with Today’s Date in PHP

In PHP, comparing dates is a common task when working with date lists or schedules. Let’s assume you have a list of dates to be compared against the current (todays) date.

The Given Date List

The provided date list is as follows:

2012-04-11
2012-04-29
2012-04-26
2012-04-23
2012-03-21
2012-07-23
2012-12-19

Each date is in the format YYYY-MM-DD.

Comparing Dates in PHP

To compare these dates with today’s date, we can use the DateTime class in PHP. Here’s a step-by-step approach:

Step 1: Create an Array of DateTime Objects

First, let’s create an array where each element is a DateTime object representing one of the given dates.

$dateList = [
    new DateTime('2012-04-11'),
    new DateTime('2012-04-29'),
    // ... other dates in the list
];

Step 2: Get Today’s Date as a DateTime Object

Next, we need to get today’s date. We can do this by creating a new DateTime object with no parameters—the constructor will automatically set it to the current date and time.

$today = new DateTime();

Step 3: Compare Each Datum in the List

Now, let’s loop through our date list and compare each date with today’s date. We’ll use the diff method of the DateTime class, which returns a DateInterval object representing the difference between two dates.

$pastDates = [];
$futureDates = [];

foreach ($dateList as $datum) {
    $interval = $today->diff($datum);

    if ($interval->invert == 1) { // If past
        $pastDates[] = $datum;
    } elseif ($interval->invert == -1) { // If future
        $futureDates[] = $datum;
    }
}

Step 4: Display the Results

Finally, let’s print out the lists of past and future dates.

echo "Past Dates:\n";
foreach ($pastDates as $date) {
    echo $date->format('Y-m-d') . "\n";
}

echo "Future Dates:\n";
foreach ($futureDates as $date) {
    echo $date->format('Y-m-d') . "\n";
}

Conclusion

With this approach, you can easily compare a list of dates with today’s date in PHP. The DateTime class provides powerful tools for working with dates, making it straightforward to determine which dates are past and which are future.

Remember that the DateInterval object returned by diff gives you information not only about whether a date is past or future but also how many days ago or ahead it is.

For more advanced date manipulation techniques, consider exploring PHP’s built-in functions for working with dates and times. You can find a comprehensive guide on https://laravelcompany.com/blog/php-date-and-time-functions.

PHP

Our network