Compare PHP date

Marc Wag­ner

Octo­ber 19, 2020

2 min read|

In this tuto­ri­al we will explain how you can compa­re two data in PHP. Com­pa­ring two data in PHP is very simp­le.

First method #

If both data have the same for­mat, the strings can be com­pared as fol­lows:

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

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

Howe­ver, the who­le thing works only with the for­mat spe­ci­fied abo­ve.

Why is that?
Let’s think of the who­le time as an inte­ger:
2020-01-01 beco­mes 20200101
2021-01-01 beco­mes 20210101

This then results in:
20210101 > 20200101 = TRUE

In Ger­man, the for­mat would look like this:
01.01.2020 beco­mes 01012020
01.01.2021 beco­mes 01012020

From this then fol­lows:
01012021 > 01012020 = TRUE

But if you use any other day or month, the who­le thing would not work any­mo­re.

01.01.2020 beco­mes 01012020
01.05.2019 beco­mes 01052019

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

Second method #

This method also makes it pos­si­ble to compa­re dif­fe­rent for­mats 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 addi­ti­on to com­pa­ring dates, this method also allows you to deter­mi­ne the dif­fe­rence bet­ween days, months and years. Fur­ther­mo­re, it uses the object-ori­en­­ted approach of PHP and should always be used if pos­si­ble.

$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 #

Bes­i­des PHP, you can also con­ve­ni­ent­ly sol­ve the com­pa­ri­son of dates on the cli­ent side. Here I have writ­ten an artic­le that shows you how the who­le thing works in Java­Script.

Conclusion #

You see, com­pa­ring two data in PHP is quite easy thanks to OOP and enables many more fea­tures.

Do you have any ques­ti­ons or comm­ents? Then feel free to lea­ve us a com­ment.

88e86fcb816eff22bc917094df2862d8dd5c0e978b333e6dd5f36f808990c261 96

Arti­kel von:

Marc Wag­ner

Hi Marc here. I’m the foun­der of Forge12 Inter­ac­ti­ve and have been pas­sio­na­te about buil­ding web­sites, online stores, appli­ca­ti­ons and SaaS solu­ti­ons for busi­nesses for over 20 years. Befo­re foun­ding the com­pa­ny, I alre­a­dy work­ed in publicly lis­ted com­pa­nies and acqui­red all kinds of know­ledge. Now I want to pass this know­ledge on to my cus­to­mers.

Hast du eine Fra­ge? Hin­ter­lass bit­te einen Kom­men­tar