John Davidson

php - loop in time using laravel 8

0 comments
Message:


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,



My Answer:
> Here is an example code snippet in Laravel 8 that loops through the time range and adds 30 minutes to each iteration:

php
$start_time = '09:00:00';
$end_time = '17:00:00';

$available_times = [];

$current_time = $start_time;

while (strtotime($current_time) <= strtotime($end_time)) {
$available_times[] = $current_time;
$current_time = date("H:i:s", strtotime($current_time) + 1800); // Add 30 minutes (1800 seconds)
}

// Output the array of available times
dd($available_times);


In this code snippet, we start with the `$start_time` and loop through until we reach the `$end_time`, adding 30 minutes to each iteration using the `strtotime` and `date` functions. The resulting array `$available_times` will contain all the times in 30-minute intervals between the start and end times.

Make sure to replace `$start_time` and `$end_time` with your actual start and end times, and adjust the time format if needed. Let me know if you need any further assistance!

Rate this post

3 of 5 based on 5282 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us