Here are two times in db in time format: "10:00:00" and "11:00:00".
I have tried to compare them:
$starttime = Carbon::parse($icomingdate['"starttime']);
$endtime = Carbon::parser($icomingdate["endtime"]);
if($starttime + 30 > $endtime && $endtime <= '23:59:00') {
echo "Greated then start time + 30 minutes";
}
How to do that properly in Carbon?
My full code is:
$date1 = ["date" => "2022-10-23", "starttime" => "10:00:00", "endtime" => "11:00:00"];
$date2 = ["date" => "2022-10-23", "starttime" => "11:00:00", "endtime" => "12:00:00"];
$icomedate = ["date" => "2022-10-23", "starttime" => "10:00:00", "endtime" => "10:30:00"];
$dates = [$date1, $date2];
try {
$starttime = Carbon::parse($icomedate["starttime"]);
$endtime = Carbon::parse($icomedate["endtime"]);
$date = Carbon::parse($icomedate["date"]);
$interval = 30;
if ($endtime < $starttime) {
throw new Error("End time should be greate start time");
}
if($endtime < $starttime->addMinutes($interval)) {
throw new Exception("Interval");
}
if($endtime > $date->endOfDay()) {
throw new Exception("End time can not be more then end of day");
}
if($starttime < $date->startOfDay()) {
throw new Exception("End time can not be less then start of day");
}
foreach ($dates as $date) {
$stime = Carbon::parse($date["starttime"]);
$etime = Carbon::parse($date["endtime"]);
if ($starttime >= $stime && $starttime <= $etime) {
throw new Exception("StartEndtime time crossed");
}
}
} catch (Exception $e) {
dd($e->getMessage());
}
So I try to check times for selected date.
2
Answers
Carbon
has comparison methods to make this possible easily. Such as :eq()
orequalTo()
– Dates are equalne()
ornotEqualTo()
– Date are not equalgt()
orgreaterThan()
orisAfter()
– Date greater than another dategte()
orgreaterThanOrEqualTo()
– Date greater than or equal to another datelt()
orlessThan()
orisBefore()
– Date less than another datelte()
orlessThanOrEqualTo()
– Date less than or equal to another datebetween()
orisBetween()
/betweenIncluded()
/betweenExcluded()
– Date is between two other datesSo for your comparison above, you can do it this way:
On your model cast your columns to dates, with the date format on the cast property.
Now your model will return dates, Carbon has a lot of comparison functions and you can use. Your endtime comparison does not make sense, as if you do not have the date as your format states, it can not be more than 23:59.