How to Check if Time Falls Within a Specific Time Range Using PHP\'s DateTime Class?

Susan Sarandon
Release: 2024-10-19 11:29:02
Original
170 people have browsed it

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>
Copy after login

Explanation:

  • The code parses the provided strings into DateTime objects using createFromFormat().
  • It then compares the current time ($date1) to both the sunrise ($date2) and sunset ($date3) times.
  • If the current time is greater than the sunrise and smaller than the sunset, it is considered to be within the specified time range.

References:

  • [PHP DateTime Class](https://www.php.net/manual/en/class.datetime.php)

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!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!