Home >Backend Development >PHP Tutorial >How to Compare Dates with a Custom 'd_m_y' Format in PHP?
Question:
How can I compare two dates in PHP that are formatted as '03_01_12' and '31_12_11'?
Attempt 1:
The provided code:
$date1 = date('d_m_y'); $date2 = '31_12_11'; if (strtotime($date1) < strtotime($date2)) echo '1 is small ='.strtotime($date1), ','.$date1; else echo '2 is small ='.strtotime($date2), ','.$date2;
Explanation:
The above code attempts to compare dates using the strtotime() function, but it's not working because it uses the system's default date format for conversion, which is not the custom format used in the date strings.
Answer:
To properly compare the dates with the given custom format, you can use the DateTime::createFromFormat() method. Here's a modified code example:
$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:
The above is the detailed content of How to Compare Dates with a Custom 'd_m_y' Format in PHP?. For more information, please follow other related articles on the PHP Chinese website!