Comparing Dates in PHP with Custom Formats
In PHP, comparing dates is a common task. However, when dealing with dates in specific formats, it can be challenging. Let's consider a scenario where dates are given in the format '03_01_12' and '31_12_11'.
Using strtotime
You attempted to compare dates using strtotime, which converts human-readable dates into timestamps. While this approach works for standard date formats, it fails with custom formats like yours.
Solution: DateTime::createFromFormat
To resolve this issue, we can utilize DateTime::createFromFormat. This function allows us to create DateTime objects from dates with custom formats. Using this function, we have the following code:
<?php $format = "d_m_y"; $date1 = \DateTime::createFromFormat($format, "03_01_12"); $date2 = \DateTime::createFromFormat($format, "31_12_11"); var_dump($date1 > $date2); ?>
In this code:
By using DateTime::createFromFormat, we can correctly compare dates in the specified custom format.
The above is the detailed content of How Can I Compare Dates with Custom Formats in PHP?. For more information, please follow other related articles on the PHP Chinese website!