使用Carbon来了解时间是否介于两个时间点之间 [英] using Carbon to know if a time falls between two points of time or not

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

问题描述

我正在使用Laravel.我刚刚遇到了供应商文件夹中已经存在的 Carbon .我进行了一些快速搜索,发现它是PHP Date时间的一个很好的扩展.

I am using Laravel. I have just come across Carbon which was already there in vendors folder. I did some quick search and found that it is a great extension from PHP Date time.

在我的应用程序中的某个地方,我需要一个逻辑来检查给定时间是否介于两个时间点之间.可以说,我要检查10:00是否在时间9:55和10:05之下.当然可以,但是我应该如何在Carbon的帮助下使用该逻辑.

Somewhere in my application, I needed a logic that will check if a given time falls between two points of time. Lets say, I want to check if 10:00 falls under the time time 9:55 and 10:05. Surely, it falls but how should I use that logic with the help of Carbon.

默认情况下, Carbon :: now()将以 2014-12-02 14:37:18 格式返回日期和时间.我在想,如果我只能提取时间部分,即 14:37:18 ,那么我可以比较两次以了解被测时间是否在两个时间点之内.

By default Carbon::now() will return date and time in 2014-12-02 14:37:18 format. I was thinking if I could extract the time part only i.e 14:37:18 then I can compare two times to know whether the time under testing falls under the two points of time or not.

如果我直接检查两个Carbon对象,它也会尝试检查年份.但是我所需要的只是时间部分.

If i directly check two Carbon objects, it will try to check the year as well. But all I need is just the time part only.

事实上,我什至不确定是否可以通过碳比较是否可以直接比较时间(h:m:s).

And as a matter of fact, I am not even sure If the times (h:m:s) can directly can be compared or not through carbon.

推荐答案

是的,在Carbon中可以做到这一点,因为只需查看文档

Yes there is a way to do this in Carbon, as just take a look on documentation here.

要确定当前实例是否在其他两个实例之间,可以使用适当命名的between()方法.第三个参数指示是否应该进行等于比较.默认值是true,它确定其是否在边界之间或等于边界.

To determine if the current instance is between two other instances you can use the aptly named between() method. The third parameter indicates if an equal to comparison should be done. The default is true which determines if its between or equal to the boundaries.

$first = Carbon::create(2012, 9, 5, 1);
$second = Carbon::create(2012, 9, 5, 5);
var_dump(Carbon::create(2012, 9, 5, 3)->between($first, $second));          // bool(true)
var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second));          // bool(true)
var_dump(Carbon::create(2012, 9, 5, 5)->between($first, $second, false));   // bool(false)

这篇关于使用Carbon来了解时间是否介于两个时间点之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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