Home >Backend Development >PHP Tutorial >How to Reliably Compare Dates in PHP, Especially Those with Non-Zero-Padded Days?
Comparing Dates in PHP: Handling Non-Zero Padded Days
When comparing dates in PHP, it's important to consider that dates stored in the database may not follow the zero-padded format (e.g., "2011-10-2"). This can lead to incorrect comparisons when using standard date comparison operators.
Solution using strtotime()
For dates after January 1st, 1970, you can use PHP's strtotime() function to compare dates:
$today = date("Y-m-d"); $expire = $row->expireDate; //from database $today_time = strtotime($today); $expire_time = strtotime($expire); if ($expire_time < $today_time) { /* do Something */ }
strtotime() converts a string representing a date and time into a UNIX timestamp, which represents the number of seconds since January 1st, 1970. This allows you to compare dates by comparing their timestamps.
Solution using DateTime Class
For PHP versions 5.2.0 and above, you can use the DateTime class to work with dates:
$today_dt = new DateTime($today); $expire_dt = new DateTime($expire); if ($expire_dt < $today_dt) { /* Do something */ }
The DateTime class provides a comprehensive set of functions for working with dates and times, including comparison operators.
Other Considerations
The above is the detailed content of How to Reliably Compare Dates in PHP, Especially Those with Non-Zero-Padded Days?. For more information, please follow other related articles on the PHP Chinese website!