Home > Article > Backend Development > How to Check if Time Falls Within a Specific Time Range Using PHP\'s DateTime Class?
Using PHP's DateTime Class to Check if Time Is Between Two Time Values
This code snippet explores a solution to determining if a given time falls within a specified range, represented by a sunrise and sunset timeframe.
Code:
<code class="php">$current_time = "4:59 pm"; $sunrise = "5:42 am"; $sunset = "6:26 pm"; $date1 = DateTime::createFromFormat('h:i a', $current_time); $date2 = DateTime::createFromFormat('h:i a', $sunrise); $date3 = DateTime::createFromFormat('h:i a', $sunset); if ($date1 > $date2 && $date1 < $date3) { echo 'The current time is between sunrise and sunset.'; }</code>
Explanation:
References:
The above is the detailed content of How to Check if Time Falls Within a Specific Time Range Using PHP\'s DateTime Class?. For more information, please follow other related articles on the PHP Chinese website!