Skip to content
PHP Logo

What are the potential pitfalls of comparing dates using the "d-m-y" format in PHP?

When comparing dates using the "d-m-y" format in PHP, a potential pitfall is that dates may not be accurately compared if they are in different years. To avoid this issue, it is recommended to use the "Y-m-d" format for date comparisons in PHP, as it ensures that dates are compared accurately regardless of the year.

php
$date1 = DateTime::createFromFormat('d-m-y', '01-01-20');
$date2 = DateTime::createFromFormat('d-m-y', '02-01-21');

if ($date1 < $date2) {
    echo "Date 1 is before Date 2";
} else {
    echo "Date 1 is after Date 2";
}