Comparing Date Strings in PHP
Suppose we have two dates in the following text format:
<?php
$date1 = '2020-12-01';
$date2 = '2019-12-01';
?>
In this case, you can compare these dates and find out which one is greater:
<?php
var_dump($date1 > $date2);
?>
How does the comparison of these dates work? The fact is that our dates are strings and PHP compares them as strings. That is, it first compares the first characters of the two dates: if they are the same, then PHP compares the second characters, and so on, until it finds a difference. Thanks to the fact that in our date format the year comes first, then the month, and then the day, such comparison is possible.
It is also important that the dates are in the same format. In our case, the separators of the date parts are dashes. This, of course, is not mandatory. For example, you can use dots:
<?php
$date1 = '2020.12.01';
$date2 = '2019.12.01';
?>
Or even remove the separators:
<?php
$date1 = '20201201';
$date2 = '20191201';
?>
The main thing for the comparison to be correct is the following placement: first the year, then the month, then the day.
Write code that will compare the two dates below and output a message about which one is greater:
$date1 = '2020-11-30';
$date2 = '2020-12-01';