PHP,如果一个小时介于其他两个小时之间 [英] PHP If an Hour Is Between Two Other Hours

查看:86
本文介绍了PHP,如果一个小时介于其他两个小时之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果当前时间在其他两个时间之间,我需要计算。例如,要检查时间是否在07:00和10:00之间,我可以使用:

I need to work out if the current hour is between two other times. For example to check if the time is between 07:00 and 10:00 I could use:

$currentTime = new DateTime('09:00');
$startTime = new DateTime('07:00');
$endTime = new DateTime('10:00');

if ($currentTime->format('H:i') >= $startTime->format('H:i') && $currentTime->format('H:i') <= $endTime->format('H:i')) {
    // Do something
}

我的问题是,如果时间是01:00,我想检查一下时间是否在22:00和07:00之间。我不介意这是另一天,即使它介于24小时制的那两个小时之间。示例01:00在22:00至07:00之间

The problem I have is what happens if the time is 01:00 and I want to check if it's between 22:00 and 07:00. I'm not bothered that that it is another day, just if it falls between those two hours on a 24hr clock. Example 01:00 is between 22:00 and 07:00

22:00、23:00、00:00, 01:00 ,02:00 ... 07:00

22:00, 23:00, 00:00, 01:00, 02:00... 07:00

我最终想要实现的是,可以为不同时间之间的服务设置不同的价格。因此,我目前遍历每个小时,计算出该小时的价格范围,并相应地更改价格。如果有人对这个问题有更优雅的解决方法,我将不胜感激。

What I'm trying to achieve in the end is different prices can be set for a service between different times. So I currently loop through each hour working out what price bracket that hour falls into and the changing the price accordingly. If anyone has a more elegant solution for the problem I would be grateful to learn.

更新:

说我有一条规则,说晚上10点到早上7点之间,我要加倍收费。我从开始时间到结束时间循环浏览每个小时,并检查每个小时是否介于22:00(10pm)和07:00(7am)之间,如果是,则应加倍收费。我想避免不得不考虑日期。

Say I have a rule that says between 10pm and 7am I want to charge double. I loop through each hour from the start time to the end time and check if each hour falls between 22:00 (10pm) and 07:00 (7am) and if so it should be charged double. I want to avoid having to take in to account the date.

推荐答案

无需使用 DateTime: :format()进行比较。 DateTime 对象已经具有可比性。

No need to use DateTime::format() for your comparisons. DateTime objects are already comparable.

要处理跨午夜的时间段,您需要更改日期,以便准确反映实际日期。

To handle working with time periods that span midnight you will need to change the date so you have an accurate reflection of the actual date.

$currentTime = (new DateTime('01:00'))->modify('+1 day');
$startTime = new DateTime('22:00');
$endTime = (new DateTime('07:00'))->modify('+1 day');

if ($currentTime >= $startTime && $currentTime <= $endTime) {
    // Do something
}

这篇关于PHP,如果一个小时介于其他两个小时之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆