How to check if a date is in a given range?
In PHP, you can use the DateTime class to check if a date is within a given range. Here is an example of how you can use it:
<?php
$start = new DateTime('2022-01-01');
$end = new DateTime('2022-12-31');
$check = new DateTime('2022-06-15');
if ($check >= $start && $check <= $end) {
echo 'The date is within the range.';
} else {
echo 'The date is not within the range.';
}
Watch a video course
Learn object oriented PHP
This example creates three DateTime objects: $start, $end, and $check. It then compares $check with $start and $end using the greater than or equal to (>=
) and less than or equal to (<=
) operators. If $check is within the range, it will print "The date is within the range." Otherwise, it will print "The date is not within the range.".