
使用 PHP 的 DateTime 类检查时间是否在两个时间值之间
此代码片段探索了一种确定给定时间是否落在的解决方案在指定范围内,以日出和日落时间范围表示。
代码:
1 2 3 4 5 6 7 8 9 | <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>
|
登录后复制
说明:
- 代码使用 createFromFormat() 将提供的字符串解析为 DateTime 对象。
- 然后将当前时间 ($date1) 与日出 ($date2) 和日落 ($date3) 时间进行比较。
- 如果当前时间大于日出且小于日落,则认为在指定时间范围内。
参考:
- [PHP 日期时间类](https://www.php.net/manual/en/class.datetime.php)
以上是如何使用 PHP 的 DateTime 类检查时间是否在特定时间范围内?的详细内容。更多信息请关注PHP中文网其他相关文章!