This question already has an answer here:
这个问题在这里已有答案:
- How to calculate the difference between two dates using PHP? 31 answers
- 如何使用PHP计算两个日期之间的差异? 31个答案
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";
Edit: I don't understand why I got so many down votes. I suppose this site is meant to ask question if you can't do something on your own.
编辑:我不明白为什么我得到这么多的选票。我想这个网站是想问你是否自己做不了什么。
I could not figure out how to convert the time to the numbers because of am/pm thats why I asked the question. I did not see any similar question so I asked.
我无法弄清楚如何将时间转换为数字因为上午/下午这就是为什么我问这个问题。我没有看到任何类似的问题,所以我问道。
2 个解决方案
#1
60
$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';
}
看到它在行动
Reference
参考
- DateTime
- 约会时间
#2
2
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,这将更容易处理,因此,如果时间是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
希望能帮助到你
#1
60
$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';
}
看到它在行动
Reference
参考
- DateTime
- 约会时间
#2
2
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,这将更容易处理,因此,如果时间是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
希望能帮助到你