如何检查时间是否在 PHP 中的两次之间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15911312/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 10:11:05  来源:igfitidea点击:

How to check if time is between two times in PHP

phptime

提问by user966582

I have following three strings (current time, sunset and sunrise), how can I find if the current time is between the sunrise and sunset?

我有以下三个字符串(当前时间,日落和日出),如何确定当前时间是否在日出和日落之间?

$current_time = "10:59 pm";
$sunrise = "5:42 am";
$sunset = "6:26 pm";

回答by John Conde

$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 'here';
}

See it in action

看到它在行动

Reference

参考

回答by Ace

i would recoment you to first "convert" the strings to integers using substr function and intval.

我建议您首先使用 substr 函数和 intval 将字符串“转换”为整数。

avter this step you should be able to simply compare the times.

在这一步之后,您应该能够简单地比较时间。

( note that you should use 18:00 instead of 6:00 PM, this would be easyer to handl, therefor you could "detect" with substr if the time is AM or PM, and just add "12" to the number )

(请注意,您应该使用 18:00 而不是 6:00 PM,这会更容易处理,因此如果时间是 AM 或 PM,您可以使用 substr“检测”,然后将“12”添加到数字中)

i'm pretty shure there are more elegant ways of doing this, but this should just give you an BASIC idea for a SIMPLE way for not advanced php developers.

我很确定有更优雅的方法可以做到这一点,但这应该只是为您提供一个基本的想法,为非高级 php 开发人员提供一种简单的方法。

hope it helps

希望能帮助到你