please i need your help to get time looping i have a start time and end time , and i want to list of array times with added 30 minutes i am trying to get code like below but array return empty
$available_times = [];
$module = $garage->work_time;
$from = date("H:i", strtotime($module->from));
$to = date("H:i", strtotime($module->to));
$time = strtotime($from);
$new_time = date("H:i", strtotime('30 minutes', $time));
if(!in_array(date("h:i a" , strtotime($new_time)), $available_times))
{
array_push($available_times , date("h:i a" , strtotime($new_time)));
}
while($new_time < $to)
{
$time = strtotime($new_time);
$new_time = date("H:i", strtotime(' 30 minutes', $new_time));
if($new_time . ':00' >= $to)
{
break;
}
if(!in_array(date("h:i a" , strtotime($new_time)), $available_times))
{
array_push($available_times , date("h:i a" , strtotime($new_time)));
}
}
return $available_times;
can any one help me i want a list like that
[
"9:30 am",
"10:00 am",
"10:30 am",
"11:00 am",
"11:30 am",
]
..etc,
CodePudding user response:
You can simply your code by using a mixture of DateTime, DatePeriod and DateInterval:
$start = new DateTime($garage->work_time->from);
$end = new DateTime($garage->work_time->to);
$interval = DateInterval::createFromDateString('30 minutes');
$period = new DatePeriod($start, $interval, $end);
$available_times = [];
foreach ($period as $time) {
$available_times[] = $time->format('h:i a');
}
return $available_times;
Alternatively, since Laravel comes with Carbon, you could use CarbonPeriod instead:
use Carbon\CarbonPeriod;
$periods = CarbonPeriod::create($garage->work_time->from, '30 minutes', $garage->work_time->to);
$available_times = array_map(function ($period) {
return $period->format('h:i a');
}, $periods->toArray());
CodePudding user response:
i solved it by change time in DB to 24 hours 17:00:00 instead of 5:00:00 in end time
$available_times = [];
$from = date("H:i", strtotime($module->from));
$to = date("H:i", strtotime($module->to));
if (!in_array(date("h:i a", strtotime($from)), $available_times)) {
array_push($available_times, date("h:i a", strtotime($from)));
}
$time_from = strtotime($from);
$new_time = date("H:i", strtotime('30 minutes', $time_from));
if (!in_array(date("h:i a", strtotime($new_time)), $available_times)) {
array_push($available_times, date("h:i a", strtotime($new_time)));
}
while ($new_time < $to) {
$time = strtotime($new_time);
$new_time = date("H:i", strtotime(' 30 minutes', $time));
if ($new_time . ':00' >= $to) {
break;
}
// //Push 3
if (!in_array(date("h:i a", strtotime($new_time)), $available_times)) {
array_push($available_times, date("h:i a", strtotime($new_time)));
}
}
return $available_times;