Compare PHP date

In this tutorial we will explain how you can compare two data in PHP. Comparing two data in PHP is very simple.

First method #

If both data have the same format, the strings can be compared as follows:

$dateOne = '2020-01-01';
$dateTwo = '2021-01-01';

if($dateTwo > $dateOne){
    echo 'Datum '.$dateTwo.' ist größer als '.$dateOne;
}

However, the whole thing works only with the format specified above.

Why is that?
Let’s think of the whole time as an integer:
2020-01-01 becomes 20200101
2021-01-01 becomes 20210101

This then results in:
20210101 > 20200101 = TRUE

In German, the format would look like this:
01.01.2020 becomes 01012020
01.01.2021 becomes 01012020

From this then follows:
01012021 > 01012020 = TRUE

But if you use any other day or month, the whole thing would not work anymore.

01.01.2020 becomes 01012020
01.05.2019 becomes 01052019

This then results in:
01052019 > 01012020 = TRUE (even though the date is in the last year).

Second method #

This method also makes it possible to compare different formats with each other.

$dateOne = '15.01.2020';
$dateTwo = '2021-01-01';

if(strtotime($dateTwo) > strtotime($dateOne)){
    echo 'Datum '.$dateTwo.' ist größer als '.$dateOne;
}

Third method (OOP) #

In addition to comparing dates, this method also allows you to determine the difference between days, months and years. Furthermore, it uses the object-oriented approach of PHP and should always be used if possible.

$dateOne = '15.01.2020';
$dateTwo = '2021-01-01';

$D1 = new DateTime($dateOne);
$D2 = new DateTime($dateTwo);

if($D2 > $D1){
    echo 'Datum '.$dateTwo.' ist größer als '.$dateOne;
}

Alternative with JavaScript #

Besides PHP, you can also conveniently solve the comparison of dates on the client side. Here I have written an article that shows you how the whole thing works in JavaScript.

Conclusion #

You see, comparing two data in PHP is quite easy thanks to OOP and enables many more features.

Do you have any questions or comments? Then feel free to leave us a comment.

Hier klicken, um den Beitrag zu bewerten
[Gesamt: 0 Durchschnitt: 0]

Leave A Comment

Title