Home > Article > Backend Development > Why is my PHP code not correctly checking if a date falls between two other dates?
PHP - Checking if a Date Falls Between Two Other Dates
Question:
A code snippet retrieved from Stack Overflow has been modified to check if today's date is within a specific range. However, the modified code is not functioning as intended.
$paymentDate = date('d/m/Y'); $contractDateBegin = date('d/m/Y', '01/01/2001'); $contractDateEnd = date('d/m/Y', '01/01/2015'); if ($paymentDate > $contractDateBegin && $paymentDate < $contractDateEnd) { echo "is between"; } else { echo "NO GO!"; }
Answer:
To resolve the issue, the strtotime() PHP function should be utilized to convert the dates to a timestamp format. This ensures that the dates are compared correctly based on their values as timestamps.
$paymentDate = date('Y-m-d'); $paymentDate = date('Y-m-d', strtotime($paymentDate)); $contractDateBegin = date('Y-m-d', strtotime("01/01/2001")); $contractDateEnd = date('Y-m-d', strtotime("01/01/2012")); if (($paymentDate >= $contractDateBegin) && ($paymentDate <= $contractDateEnd)) { echo "is between"; } else { echo "NO GO!"; }
Note:
To ensure today's date is included in the comparison, use >= and <= instead of > and <.
The above is the detailed content of Why is my PHP code not correctly checking if a date falls between two other dates?. For more information, please follow other related articles on the PHP Chinese website!