Home > Article > Backend Development > How to Check if a Date Falls Between Two Dates in PHP?
PHP Check if Date Between Two Dates
In PHP, you can efficiently determine if a given date falls between two specified dates. To address the issue raised, let's examine the code.
The provided code defines three date variables: $paymentDate, $contractDateBegin, and $contractDateEnd. The $paymentDate variable is set to the current date using the date() function. However, it uses the d/m/Y format, which may not yield the desired result.
To ensure correct formatting, utilize the strtotime() function to convert the $paymentDate variable to the Y-m-d format. This format is conducive for comparisons in PHP.
The code also employs the > and < operators to check if the $paymentDate falls between the $contractDateBegin and $contractDateEnd. To account for today's date, adjust the code as follows:
$paymentDate = date('Y-m-d', strtotime(date('Y-m-d'))); $contractDateBegin = date('Y-m-d', strtotime('01/01/2001')); $contractDateEnd = date('Y-m-d', strtotime('01/01/2015')); if ((($paymentDate >= $contractDateBegin) && ($paymentDate <= $contractDateEnd))) { echo "is between"; } else { echo "NO GO!"; }
The >= and <= operators ensure that today's date is also considered in the check. By making these adjustments, the code will accurately determine if the current date falls within the specified date range.
The above is the detailed content of How to Check if a Date Falls Between Two Dates in PHP?. For more information, please follow other related articles on the PHP Chinese website!