php - using Carbon to know if a time falls between two points of time or not
Get the solution ↓↓↓I am using Laravel. I have just come acrossCarbon
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 defaultCarbon::now()
will return date and time in2014-12-02 14:37:18
format. I was thinking if I could extract the time part only i.e14: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.
Answer
Solution:
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)
Answer
Solution:
UNIX time is easier for this sort of task.
So you could use strtotime to convert your hipster representation to neckbeard representation and compare like a real man. Since you only want to compare hours, you can hack this by using a relative time.
<?php
$now = time();
$startTime = strtotime( "12:10:24", $now );
$endTime = strtotime( "14:24:45", $now );
$point = strtotime("12:25:40", $now );
if( $point >= $startTime && $point <= $endTime )
{
echo "Inside\n";
} else {
echo "Outside\n";
}
?>
Output:
$ php test.php 2> /dev/null
Inside
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: illegal string offset
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.