Home > Backend Development > PHP Tutorial > Why is my PHP code not correctly checking if a date falls between two other dates?

Why is my PHP code not correctly checking if a date falls between two other dates?

Mary-Kate Olsen
Release: 2024-11-17 17:09:02
Original
502 people have browsed it

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!";
}
Copy after login

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!";
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template