使用碳知道一个时间是否在两点之内 [英] using Carbon to know if a time falls under two points of time or not

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

问题描述

我正在使用Laravel。我刚刚遇到已经在供应商文件夹中的 Carbon 。我做了一些快速搜索,发现它是PHP Date时间的一个很好的延伸。



在我的应用程序中,我需要一个逻辑,检查一个给定的时间是否下降两点之间。让我们说,我想检查10:00是否在时间9:55和10:05的时间。当然,它落后,但我应该如何在碳的帮助下使用这个逻辑。



默认情况下 Carbon :: now()将在 2014- 12-02 14:37:18 格式。我正在想,如果我可以提取时间部分,即 14:37:18 然后我可以比较两次,以了解被测时间是否落在两个时间点之下或者不是。



如果我直接检查两个Carbon对象,它也会尝试检查年份。但我所需要的只是时间部分。事实上,我甚至不确定如果时间(h:m:s)可以直接通过碳来比较。

解决方案

有没有办法在Carbon中做到这一点,只需查看文档这里


要确定当前实例是否在另外两个实例可以使用适当命名的()方法。第三个参数表示是否应该进行相等的比较。默认值为true,确定它是否在边界之间或之间。




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


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.

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.

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.

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.

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.

解决方案

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

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)

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

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