Comparing Dates in PHP with Custom Formats
When comparing dates that are not in standard formats, such as '03_01_12' and '31_12_11', the strtotime() function may not provide accurate results. To overcome this, you can use the DateTime class to specify a custom date format.
<?php // Create a custom date format $format = "d_m_y"; // Create DateTime objects for the given dates $date1 = \DateTime::createFromFormat($format, "03_01_12"); $date2 = \DateTime::createFromFormat($format, "31_12_11"); // Compare the DateTime objects var_dump($date1 > $date2); ?>
In this code, the DateTime::createFromFormat() function takes two parameters: the custom format and the date string. It creates DateTime objects that represent the dates in the given format. The comparison operator > checks if the first date is greater than the second date.
The above is the detailed content of How Can I Reliably Compare Dates with Non-Standard Formats in PHP?. For more information, please follow other related articles on the PHP Chinese website!