i need array like example if can set option for step,start,end is very better
[
[
"07:30:00",
"08:00:00",
],
[
"08:00:00",
"08:30:00",
],
....
[
"23:30:00",
"00:00:00",
],
]
CodePudding user response:
The best solution I guess is:
function timeSteps($step, $start, $end){
$stepHours = substr($step, 0, 2);
$stepMinutes = substr($step, 3, 2);
$stepSeconds = substr($step, 6, 2);
$startTime = Carbon::createFromFormat('H:i:s', $start);
$endTime = Carbon::createFromFormat('H:i:s', $end);
$result = [];
while ($startTime->lt($endTime)) {
$item = [];
array_push($item, $startTime->format('H:i:s'));
$startTime->addHours($stepHours);
$startTime->addMinutes($stepMinutes);
$startTime->addSeconds($stepSeconds);
array_push($item, $startTime->format('H:i:s'));
array_push($result, $item);
}
return $result;
}
And you can call it like:
timeSteps("00:30:00", "08:00:00", "10:00:00")
CodePudding user response:
i do this in laravel and result is ok
function range($lower = 0, $upper = 86400, $step = 3600, $format = '')
{
$times = array();
if ( empty( $format ) ) {
$format = 'g:i a';
}
foreach ( range( $lower, $upper, $step ) as $increment ) {
$increment = gmdate( 'H:i', $increment );
list( $hour, $minutes ) = explode( ':', $increment );
$date = new \DateTime( $hour . ':' . $minutes );
$times[] = $date->format( $format );
}
$times = collect($times)->chunk(2)->map(function($item) {
return $item->values();
});
$new_times = [];
foreach ($times as $key=>$time){
if($key == 0){
$new_times[$key][0] = $time[0];
$new_times[$key][1] = $time[1];
}
else{
$new_times[$key][0] = Carbon::parse($time[0])->subMinutes(30*$key)->format('H:i:s');
$new_times[$key][1] = Carbon::parse($time[1])->subMinutes(30*$key)->format('H:i:s');
}
}
return $new_times;
}
and use :
range(27000, 144000, 1800, 'H:i:s');
CodePudding user response:
There are few possibilities here, but this method will keep it simple... Create a function to create your sub-array start and end times. Then, create a range of start and end times, eg: 8:00am to midnight. By incrementing each by 1800 seconds (half hour) you will get your result..
<?php
function timeRange( $start = 0, $end = 86400, $step = 3600, $format = 'Y-m-d H:i:s' ) {
$times = [];
foreach ( range( $start, $end, $step ) as $inc ) {
$inc = gmdate( 'H:i', $inc );
$date = new DateTime( $inc );
$times[(string) $inc] = $date->format( $format );
}
return $times;
}
$my_times = [];
$range = range(28800, 84600, 1800);
foreach($range as $seconds)
{
$start = $seconds;
$end = $seconds 1800;
$my_times[] = timeRange($seconds, $end, 1800, 'H:i:s');
}
var_dump($my_times);