Reputation: 85
I am trying to make a function in Laravel 5.6
I have a $start_time
, $end_time
and $duration
variables.
I would like to get time slots from the start time until end time, in $duration
periods, for example:
$duration = 30 min
$start_time = 9:00 am
$end_time = 9:00 pm
Results:
-9:00 - 9:30
-9:30 - 10:00
-10:00 - 10:30
.... etc
Also, I would like to not show the slot where time overlaps with appointments in my database.
Upvotes: 0
Views: 5310
Reputation: 892
$starttime = '9:00'; // your start time
$endtime = '21:00'; // End time
$duration = '30'; // split by 30 mins
$array_of_time = array ();
$start_time = strtotime ($starttime); //change to strtotime
$end_time = strtotime ($endtime); //change to strtotime
$add_mins = $duration * 60;
while ($start_time <= $end_time) // loop between time
{
$array_of_time[] = date ("h:i", $start_time);
$start_time += $add_mins; // to check endtie=me
}
$new_array_of_time = array ();
for($i = 0; $i < count($array_of_time) - 1; $i++)
{
$new_array_of_time[] = '' . $array_of_time[$i] . ' - ' . $array_of_time[$i + 1];
}
Upvotes: 2
Reputation: 112
If you are using Laravel there is a dependency for times&dates called Carbon I'm sure you've heard of.
all you have to do is importing it like that:
use Carbon\Carbon;
Then we can see what will we do by this dependency, we just create a time then add minutes to it according to duration, that is what you want to.
$start_time = Carbon::createFromTime(9, 0, 0); // hours, minutes, seconds
$end_time = Carbon::createFromTime(21, 0, 0);
$time = $start_time;
$time_slots = array();
while($time < $end_time){
$time = $time->addMinutes(30);
$time_slots[] = $time;
}
This array will have the time slots you want and you can manipulate them whatever you like.
You can also look at this links below:
Documentation: https://github.com/briannesbitt/Carbon
String formats for Carbon: http://carbon.nesbot.com/docs/#api-formatting
Upvotes: 1