Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
309 views
in Technique[技术] by (71.8m points)

php - using Carbon to know if a time falls between two points of time or not

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...