I made this Code to make time slots:
$duration = 60;
$cleanup = 0;
$start = "10:00";
$end = '24:00';
function timeslots($duration, $cleanup, $start, $end)
{
$start = new DateTime($start);
$end = new DateTime($end);
$interval = new DateInterval('PT' . $duration . 'M');
$cleanupinterval = new DateInterval('PT' . $cleanup . 'M');
$slots = array();
for ($intStart = $start; $intStart < $end; $intStart->add($interval)->add($cleanupinterval)) {
$endperiod = clone $intStart;
$endperiod->add($interval);
if ($endperiod > $end) {
break;
}
$slots[] = $intStart->format('H:iA') . '-' . $endperiod->format('H:iA');
}
return $slots;
}
?>
above code get results like this:
10:00 AM - 11:00 AM.
11:00 AM - 12:00 PM.
what I'm trying to do is something like this:
12:00 AM - 01:00 AM
01:00 AM - 02:00 AM
3. 10:00 AM - 11:00 AM
11:00 AM - 12:00 PM.
So I'm trying to make break time from 02:00 AM to 10:00 AM
so the day will start like:
12:00 AM To 02:00 AM and take breake hours from 02:00 AM To 10:00 AM.
Thanks in advance.
I Hope this will help You:
$duration = 60;
$cleanup = 0;
$start = "00:00";
$end = '24:00';
$break_start = '02:00'; // break start
$break_end = '10:00'; // break end
function timeslots($duration, $cleanup, $start, $end, $break_start, $break_end)
{
$start = new DateTime($start);
$end = new DateTime($end);
$break_start = new DateTime($break_start);
$break_end = new DateTime($break_end);
$interval = new DateInterval('PT' . $duration . 'M');
$cleanupinterval = new DateInterval('PT' . $cleanup . 'M');
$slots = array();
for ($intStart = $start; $intStart < $end; $intStart->add($interval)->add($cleanupinterval)) {
$endperiod = clone $intStart;
$endperiod->add($interval);
if (strtotime($break_start->format('H:i A')) < strtotime($endperiod->format('H:i A')) && strtotime($endperiod->format('H:i A')) < strtotime($break_end->format('H:i A'))) {
$endperiod = $break_start;
$slots[] = $intStart->format('H:i A') . ' - ' . $endperiod->format('H:i A');
$intStart = $break_end;
$endperiod = $break_end;
$intStart->sub($interval);
}
$slots[] = $intStart->format('H:iA') . '-' . $endperiod->format('H:iA');
}
return $slots;
}
and
$time_slots = timeslots($duration, $cleanup, $start, $end, $break_start, $break_end);
echo '<pre>';
print_r($time_slots);
echo '<pre>';
the result will be :
Array
(
[0] => 00:00 AM - 01:00 AM
[1] => 01:00 AM - 02:00 AM
[2] => 02:00 AM - 02:00 AM
[3] => 10:00 AM - 11:00 AM
[4] => 11:00 AM - 12:00 PM
[5] => 12:00 PM - 13:00 PM
[6] => 13:00 PM - 14:00 PM
[7] => 14:00 PM - 15:00 PM
[8] => 15:00 PM - 16:00 PM
[9] => 16:00 PM - 17:00 PM
[10] => 17:00 PM - 18:00 PM
[11] => 18:00 PM - 19:00 PM
[12] => 19:00 PM - 20:00 PM
[13] => 20:00 PM - 21:00 PM
[14] => 21:00 PM - 22:00 PM
[15] => 22:00 PM - 23:00 PM
[16] => 23:00 PM - 00:00 AM
)
Something like that?
function show_time_slots($start_time, $end_time, $duration, $break){
$time_slots = array();
$start_time = strtotime($start_time);
$end_time = strtotime($end_time);
$add_mins = $duration * 60;
while ($start_time <= $end_time)
{
$time_slots[] = date("H:i", $start_time);
$start_time += $add_mins;
}
$time_slots = array_diff( $time_slots, $break );
return $time_slots;
}
And
$start_time = '00:00';
$end_time = '23:00';
$duration = '60';
$break = ['03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00'];
$time_slots = show_time_slots($start_time, $end_time, $duration, $break);
echo '<pre>';
print_r($time_slots);
echo '</pre>';
Return
Array
(
[0] => 00:00
[1] => 01:00
[2] => 02:00
[10] => 10:00
[11] => 11:00
[12] => 12:00
[13] => 13:00
[14] => 14:00
[15] => 15:00
[16] => 16:00
[17] => 17:00
[18] => 18:00
[19] => 19:00
[20] => 20:00
[21] => 21:00
[22] => 22:00
[23] => 23:00
)
I tried to make a function that will help you to make all possible slots. the function will take the start_time and end_time and based on the duration(in minutes) it will make the slots and it will not create a slot during break time also you can add clean-up or refresh time after every slot if you want that argument will take time in minutes.
I also see that the approved answer of #Khaled Mostafa where copied by a lot of bloggers and they just copy and paste his answer in the same requirement as mine but it didn't help me in this kind of my requirement so after spending some hours I have found this solution.
function show_time_slots($start_time, $end_time, $duration, $break_start, $break_end, $cleanup = 0){
$time_slots = array();
$start_time = strtotime($start_time);
$end_time = strtotime($end_time);
$break_start = strtotime($break_start);
$break_end = strtotime($break_end);
$add_mins = ($duration + $cleanup) * 60;
while ($start_time <= $end_time)
{
$startSlotTime = date("h:i A", $start_time); // for 24 format date("H:i", $start_time);
$slotEndTime = $start_time + $add_mins;
$endSlotTime = date("h:i A", $slotEndTime); // for 24 format date("H:i", $slotEndTime);
// $sachin = strtotime($startSlotTime);
if($slotEndTime <= $end_time){
if(
($start_time > $break_start && $start_time < $break_end ) || ($slotEndTime > $break_start && $slotEndTime < $break_end )
|| ($break_start > $start_time && $break_start < $slotEndTime) || ($break_end > $start_time && $break_end < $slotEndTime)
){
$start_time = $break_end;
}else{
$time_slots[] = $startSlotTime . "-" . $endSlotTime;
$start_time += $add_mins;
}
}else{
$start_time += $add_mins;
}
}
// $time_slots = array_diff( $time_slots, $break );
return $time_slots;
}
$duration = 180; // minutes
$cleanup = 0; // minutes
$start_time = "10:00";
$end_time = '23:00';
$break_start = '16:00'; // break start
$break_end = '16:30'; // break end
$time_slots = show_time_slots($start_time, $end_time, $duration, $break_start, $break_end, $cleanup);
echo '<pre>';
print_r($time_slots);
echo '</pre>';
Out Put
Array
(
[0] => 10:00 AM-01:00 PM
[1] => 01:00 PM-04:00 PM
[2] => 04:30 PM-07:30 PM
[3] => 07:30 PM-10:30 PM
)
I am getting solution for multiple break too. pleas check my answer and tell me if anything wrong with this. no doubt I am using code of #Sachin Sarola I just changes few line as I required for multiple break slot.
function show_time_slots($start_time, $end_time, $duration, $break_arr, $cleanup = 0){
$time_slots = array();
$start_time = strtotime($start_time);
$end_time = strtotime($end_time);
$add_mins = ($duration + $cleanup) * 60;
while ($start_time <= $end_time)
{
$startSlotTime = date("h:i A", $start_time); // for 24 format date("H:i", $start_time);
$slotEndTime = $start_time + $add_mins;
$endSlotTime = date("h:i A", $slotEndTime); // for 24 format date("H:i", $slotEndTime);
if($slotEndTime <= $end_time){
$is_break = false;
$last_break_end_time = null;
foreach($break_arr as $key => $break){
$break_start = strtotime($break['break_start']);
$break_end = strtotime($break['break_end']);
if(
($start_time > $break_start && $start_time < $break_end ) || ($slotEndTime > $break_start && $slotEndTime < $break_end )
|| ($break_start > $start_time && $break_start < $slotEndTime) || ($break_end > $start_time && $break_end < $slotEndTime)
){
$is_break = true;
$last_break_end_time = $break_end;
break;
}
}
if($is_break && $last_break_end_time){
$start_time = $last_break_end_time;
}else{
$time_slots[] = $startSlotTime . "-" . $endSlotTime;
$start_time += $add_mins;
}
}else{
$start_time += $add_mins;
}
}
// $time_slots = array_diff( $time_slots, $break );
return $time_slots;
}
$duration = 180;
$cleanup = 0;
$start_time = "10:00";
$end_time = '23:00';
$break_start = '16:00'; // break start
$break_end = '16:30'; // break end
$break_arr = [
['break_start' => '16:00', 'break_end' => '16:30'],
['break_start' => '19:30', 'break_end' => '20:00']
];
$time_slots = show_time_slots($start_time, $end_time, $duration, $break_arr, $cleanup);
echo '<pre>';
print_r($time_slots);
echo '</pre>';
Out Put
Array
(
[0] => 10:00 AM-01:00 PM
[1] => 01:00 PM-04:00 PM
[2] => 04:30 PM-07:30 PM
[3] => 08:00 PM-11:00 PM
)
Related
$course_hour = 1; $starttime = '07:00'; $endtime = '16:00';
I wish if it could return an array of values like below:
If
$course_hour = 1;
$return_array = array('07:00 - 08:00', '08:00 - 09:00', '09:00 - 10:00', '10:00 - 11:00', '11:00 - 12:00', '12:00 - 13:00', '13:00 - 14:00', '14:00 - 15:00', '15:00 - 16:00');
If
$course_hour = 1.5;
$return_array = array('07:00 - 08:30', '8:30 - 10:00', '10:00 - 11:30', '11:30 - 13:00', '13:00 - 14:30', '14:30 - 16:00');
If
$course_hour = 2;
$return_array = array('07:00 - 09:00', '09:00 - 11:00', '11:00 - 13:00', '13:00 - 15:00');
function get_session_times($course_hour, $start_time, $end_time){
if(strlen($start_time) < 5) $start_time = '0'.$start_time;
if(strlen($end_time) < 5) $end_time = '0'.$end_time;
$current_time = date("Y-m-d H:i");
$session_starttime = date("Y-m-d H:i", strtotime(date("Y-m-d ").$start_time));
$session_endtime = date("Y-m-d H:i", strtotime(date("Y-m-d ").$end_time));
$session_starttime_ms = strtotime($session_starttime);
$session_endtime_ms = strtotime($session_endtime);
$session_times_array = array();
for ($i = $session_starttime_ms; $i < $session_endtime_ms; ) {
$session_times_array[] = date("H:i", $i)."<br/>";
$i = $i + ($course_hour * 60 * 60);
}
return $session_times_array;
}
/**
* Get session times from start to end.
*
* #link https://stackoverflow.com/a/27497314/128761 Convert decimal to hour and minute.
* #link https://stackoverflow.com/a/62064286/128761 Original source code for get session times.
* #param int|float|double|decimal $course_hour Course hour.
* #param string $start_time Start time. Format is Hour:minute HH:MM.
* #param string $end_time End time.
* #return array Return times in array.
*/
function getSessionTimes($course_hour, $start_time, $end_time): array
{
if (!is_numeric($course_hour)) {
return [];
}
if (empty($start_time) || empty($end_time)) {
return [];
}
$courseHour = (int) $course_hour;
$courseMinute = (fmod($course_hour, 1) * 60);
$beginDate = new DateTime(date('Y-m-d') . ' ' . $start_time);
$endDate = new DateTime(date('Y-m-d') . ' ' . $end_time);
$result = [];
while ($beginDate < $endDate) {
$output = $beginDate->format('H:i') . ' - ';
$beginDate->modify('+' . $courseHour . 'hour ' . $courseMinute . 'minute');
if ($beginDate > $endDate) {
break;
}
$output .= $beginDate->format('H:i');
$result[] = $output;
unset($output);
}
unset($beginDate, $endDate);
return $result;
}
You have to convert from decimal (for example 1, 1.5) to be hour and minute based on code from this answer.
And then I use code from this answer mentioned by mickmackusa to get times array.
Here is testing.
/**
* This function is for test the result only. It is no need in your real project.
*/
function testResult($result, $expect)
{
if (!is_array($result) || !is_array($expect)) {
throw new Exception('The result and expect must be array.');
}
$totalResult = count($result);
$totalExpect = count($expect);
$totalTested = ($totalResult === $totalExpect);
unset($totalResult, $totalExpect);
foreach ($result as $index => $eachResult) {
if (isset($expect[$index]) && $expect[$index] === $eachResult) {
// matched.
} else {
throw new Exception('The result and expect at index ' . $index . ' does not matched. (' . $eachResult . ')');
}
}
return $totalTested;
}
// run tests
$result = getSessionTimes(1, '07:00', '16:00');
$expect = ['07:00 - 08:00', '08:00 - 09:00', '09:00 - 10:00', '10:00 - 11:00', '11:00 - 12:00', '12:00 - 13:00', '13:00 - 14:00', '14:00 - 15:00', '15:00 - 16:00'];
print_r($result);
var_dump(testResult($result, $expect));
$result = getSessionTimes(1.5, '07:00', '16:00');
$expect = ['07:00 - 08:30', '08:30 - 10:00', '10:00 - 11:30', '11:30 - 13:00', '13:00 - 14:30', '14:30 - 16:00'];
print_r($result);
var_dump(testResult($result, $expect));
$result = getSessionTimes(2, '07:00', '16:00');
$expect = ['07:00 - 09:00', '09:00 - 11:00', '11:00 - 13:00', '13:00 - 15:00'];
print_r($result);
var_dump(testResult($result, $expect));
The result will be...
Array ( [0] => 07:00 - 08:00 [1] => 08:00 - 09:00 [2] => 09:00 - 10:00 [3] => 10:00 - 11:00 [4] => 11:00 - 12:00 [5] => 12:00 - 13:00 [6] => 13:00 - 14:00 [7] => 14:00 - 15:00 [8] => 15:00 - 16:00 )
boolean true
Array ( [0] => 07:00 - 08:30 [1] => 08:30 - 10:00 [2] => 10:00 - 11:30 [3] => 11:30 - 13:00 [4] => 13:00 - 14:30 [5] => 14:30 - 16:00 )
boolean true
Array ( [0] => 07:00 - 09:00 [1] => 09:00 - 11:00 [2] => 11:00 - 13:00 [3] => 13:00 - 15:00 )
boolean true
<?php
$course_hour = 1.5; // 1 || 1.5 || 2
$starttime = '07:00';
$endtime = '16:00';
print_r(get_time_range($course_hour, $starttime, $endtime));
function get_time_range($course_hour, $starttime, $endtime){
$to_add = '';
switch($course_hour):
case 1:
$to_add = " +1 hours";
break;
case 1.5:
$to_add = " +1 hours 30 minutes";
break;
case 2:
$to_add = " +2 hours";
break;
default:
$to_add = " +1 hours";
break;
endswitch;
// get the total hours
$from_time = strtotime($starttime);
$to_time = strtotime($endtime);
$diff_mins = round(abs($from_time - $to_time)/60);
$diff_hours = $diff_mins/60;
$hours_arr =[];
for($i=1; $i<=$diff_hours; $i+= $course_hour):
$new_end_strtime = strtotime($starttime . $to_add);
$endtime = date('H:i', $new_end_strtime);
if($new_end_strtime <= $to_time): // checking the last end time is not greater than defined $endtime
$str = $starttime . ' - '. $endtime;
$tmp = strtotime($starttime . $to_add);
$starttime = date('H:i', $tmp);
array_push($hours_arr, $str);
endif;
endfor;
return $hours_arr;
}
?>
I needed a list of times like so in an array...
12am
12:30am
1:00pm
...
How can I do this with PHP?
Here's an improved version of Alex's function that uses seconds for more precision:
function hoursRange( $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[(string) $increment] = $date->format( $format );
}
return $times;
}
So, to make an array of times with 1-hour intervals over a 24-hour time period, use the defaults:
hoursRange();
Which will give you the following:
Array
(
[00:00] => 12:00 am
[01:00] => 1:00 am
[02:00] => 2:00 am
[03:00] => 3:00 am
[04:00] => 4:00 am
[05:00] => 5:00 am
[06:00] => 6:00 am
[07:00] => 7:00 am
[08:00] => 8:00 am
[09:00] => 9:00 am
[10:00] => 10:00 am
[11:00] => 11:00 am
[12:00] => 12:00 pm
[13:00] => 1:00 pm
[14:00] => 2:00 pm
[15:00] => 3:00 pm
[16:00] => 4:00 pm
[17:00] => 5:00 pm
[18:00] => 6:00 pm
[19:00] => 7:00 pm
[20:00] => 8:00 pm
[21:00] => 9:00 pm
[22:00] => 10:00 pm
[23:00] => 11:00 pm
)
Here are a few example uses:
// Every 15 Minutes, All Day Long
$range = hoursRange( 0, 86400, 60 * 15 );
// Every 30 Minutes from 8 AM - 5 PM, using Custom Time Format
$range = hoursRange( 28800, 61200, 60 * 30, 'h:i a' );
You can view a working snippet at CodePad.
Thank-you for reopening the question alex.
This is a solution that should resonate with functional programmers.
function halfHourTimes() {
$formatter = function ($time) {
if ($time % 3600 == 0) {
return date('ga', $time);
} else {
return date('g:ia', $time);
}
};
$halfHourSteps = range(0, 47*1800, 1800);
return array_map($formatter, $halfHourSteps);
}
I decided this one was better :)
function hoursRange($lower = 0, $upper = 23, $step = 1, $format = NULL) {
if ($format === NULL) {
$format = 'g:ia'; // 9:30pm
}
$times = array();
foreach(range($lower, $upper, $step) as $increment) {
$increment = number_format($increment, 2);
list($hour, $minutes) = explode('.', $increment);
$date = new DateTime($hour . ':' . $minutes * .6);
$times[(string) $increment] = $date->format($format);
}
return $times;
}
We can simply use strtotime to increment our time by N amount here in this case 30 minutes and date function to format it to our desired output.
$startTime = strtotime('12 am');
$endTime = strtotime('11:59 pm');
$arrInterval = [];
while($endTime >= $startTime){
$arrInterval[] = date("h:ia", $startTime);
$startTime = strtotime('+30 minutes', $startTime);
}
Here is my suggestion :
$start = new \DateTime('00:00');
$times = 24 * 2; // 24 hours * 30 mins in an hour
for ($i = 0; $i < $times-1; $i++) {
$result[] = $start->add(new \DateInterval('PT30M'))->format('H:i A');
}
print_r($result);
Hope this help.
This is maybe a more elegant way, but it requires the times to be in seconds (that also makes it more flexible).
function time_range( $start, $end, $step = 1800 ) {
$return = array();
for( $time = $start; $time <= $end; $time += $step )
$return[] = date( 'g:ia', $time );
return $return;
}
Simplest solution
$h = 0;
while ($h < 24) {
$key = date('H:i', strtotime(date('Y-m-d') . ' + ' . $h . ' hours'));
$value = date('h:i A', strtotime(date('Y-m-d') . ' + ' . $h . ' hours'));
$formatter[$key] = $value;
$h++;
}
Result are:
Array
(
[00:00] => 12:00 AM
[01:00] => 01:00 AM
[02:00] => 02:00 AM
[03:00] => 03:00 AM
[04:00] => 04:00 AM
[05:00] => 05:00 AM
[06:00] => 06:00 AM
[07:00] => 07:00 AM
[08:00] => 08:00 AM
[09:00] => 09:00 AM
[10:00] => 10:00 AM
[11:00] => 11:00 AM
[12:00] => 12:00 PM
[13:00] => 01:00 PM
[14:00] => 02:00 PM
[15:00] => 03:00 PM
[16:00] => 04:00 PM
[17:00] => 05:00 PM
[18:00] => 06:00 PM
[19:00] => 07:00 PM
[20:00] => 08:00 PM
[21:00] => 09:00 PM
[22:00] => 10:00 PM
[23:00] => 11:00 PM
)
Here's a more flexible version that doesn't need DateTime (since we're already working with timestamps in seconds anyway). ;-)
function get_hours_range( $start = 0, $end = 86400, $step = 3600, $format = 'g:i a' ) {
$times = array();
foreach ( range( $start, $end, $step ) as $timestamp ) {
$hour_mins = gmdate( 'H:i', $timestamp );
if ( ! empty( $format ) )
$times[$hour_mins] = gmdate( $format, $timestamp );
else $times[$hour_mins] = $hour_mins;
}
return $times;
}
Added index value as hour:
Here is the code:
<?php
$time_slot= array();
if ( empty( $format ) ) {
$format = 'H:i';
}
$lower = 0; $upper = 86400; $step = 3600; $format = '';
$i = 0;
foreach ( range( $lower, $upper, $step ) as $increment ) {
$increment = gmdate( 'H:i', $increment );
$time_slot[$i] = $increment;
$i++;
}
print_r($time_slot);
?>
Here is the result:
Array
(
[0] => 00:00
[1] => 01:00
[2] => 02:00
[3] => 03:00
[4] => 04:00
[5] => 05:00
[6] => 06:00
[7] => 07:00
[8] => 08:00
[9] => 09:00
[10] => 10:00
[11] => 11:00
[12] => 12:00
[13] => 13:00
[14] => 14:00
[15] => 15:00
[16] => 16:00
[17] => 17:00
[18] => 18:00
[19] => 19:00
[20] => 20:00
[21] => 21:00
[22] => 22:00
[23] => 23:00
[24] => 00:00
)
I needed a list of times like so in an array...
12am
12:30am
1:00pm
...
How can I do this with PHP?
Here's an improved version of Alex's function that uses seconds for more precision:
function hoursRange( $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[(string) $increment] = $date->format( $format );
}
return $times;
}
So, to make an array of times with 1-hour intervals over a 24-hour time period, use the defaults:
hoursRange();
Which will give you the following:
Array
(
[00:00] => 12:00 am
[01:00] => 1:00 am
[02:00] => 2:00 am
[03:00] => 3:00 am
[04:00] => 4:00 am
[05:00] => 5:00 am
[06:00] => 6:00 am
[07:00] => 7:00 am
[08:00] => 8:00 am
[09:00] => 9:00 am
[10:00] => 10:00 am
[11:00] => 11:00 am
[12:00] => 12:00 pm
[13:00] => 1:00 pm
[14:00] => 2:00 pm
[15:00] => 3:00 pm
[16:00] => 4:00 pm
[17:00] => 5:00 pm
[18:00] => 6:00 pm
[19:00] => 7:00 pm
[20:00] => 8:00 pm
[21:00] => 9:00 pm
[22:00] => 10:00 pm
[23:00] => 11:00 pm
)
Here are a few example uses:
// Every 15 Minutes, All Day Long
$range = hoursRange( 0, 86400, 60 * 15 );
// Every 30 Minutes from 8 AM - 5 PM, using Custom Time Format
$range = hoursRange( 28800, 61200, 60 * 30, 'h:i a' );
You can view a working snippet at CodePad.
Thank-you for reopening the question alex.
This is a solution that should resonate with functional programmers.
function halfHourTimes() {
$formatter = function ($time) {
if ($time % 3600 == 0) {
return date('ga', $time);
} else {
return date('g:ia', $time);
}
};
$halfHourSteps = range(0, 47*1800, 1800);
return array_map($formatter, $halfHourSteps);
}
I decided this one was better :)
function hoursRange($lower = 0, $upper = 23, $step = 1, $format = NULL) {
if ($format === NULL) {
$format = 'g:ia'; // 9:30pm
}
$times = array();
foreach(range($lower, $upper, $step) as $increment) {
$increment = number_format($increment, 2);
list($hour, $minutes) = explode('.', $increment);
$date = new DateTime($hour . ':' . $minutes * .6);
$times[(string) $increment] = $date->format($format);
}
return $times;
}
We can simply use strtotime to increment our time by N amount here in this case 30 minutes and date function to format it to our desired output.
$startTime = strtotime('12 am');
$endTime = strtotime('11:59 pm');
$arrInterval = [];
while($endTime >= $startTime){
$arrInterval[] = date("h:ia", $startTime);
$startTime = strtotime('+30 minutes', $startTime);
}
Here is my suggestion :
$start = new \DateTime('00:00');
$times = 24 * 2; // 24 hours * 30 mins in an hour
for ($i = 0; $i < $times-1; $i++) {
$result[] = $start->add(new \DateInterval('PT30M'))->format('H:i A');
}
print_r($result);
Hope this help.
This is maybe a more elegant way, but it requires the times to be in seconds (that also makes it more flexible).
function time_range( $start, $end, $step = 1800 ) {
$return = array();
for( $time = $start; $time <= $end; $time += $step )
$return[] = date( 'g:ia', $time );
return $return;
}
Simplest solution
$h = 0;
while ($h < 24) {
$key = date('H:i', strtotime(date('Y-m-d') . ' + ' . $h . ' hours'));
$value = date('h:i A', strtotime(date('Y-m-d') . ' + ' . $h . ' hours'));
$formatter[$key] = $value;
$h++;
}
Result are:
Array
(
[00:00] => 12:00 AM
[01:00] => 01:00 AM
[02:00] => 02:00 AM
[03:00] => 03:00 AM
[04:00] => 04:00 AM
[05:00] => 05:00 AM
[06:00] => 06:00 AM
[07:00] => 07:00 AM
[08:00] => 08:00 AM
[09:00] => 09:00 AM
[10:00] => 10:00 AM
[11:00] => 11:00 AM
[12:00] => 12:00 PM
[13:00] => 01:00 PM
[14:00] => 02:00 PM
[15:00] => 03:00 PM
[16:00] => 04:00 PM
[17:00] => 05:00 PM
[18:00] => 06:00 PM
[19:00] => 07:00 PM
[20:00] => 08:00 PM
[21:00] => 09:00 PM
[22:00] => 10:00 PM
[23:00] => 11:00 PM
)
Here's a more flexible version that doesn't need DateTime (since we're already working with timestamps in seconds anyway). ;-)
function get_hours_range( $start = 0, $end = 86400, $step = 3600, $format = 'g:i a' ) {
$times = array();
foreach ( range( $start, $end, $step ) as $timestamp ) {
$hour_mins = gmdate( 'H:i', $timestamp );
if ( ! empty( $format ) )
$times[$hour_mins] = gmdate( $format, $timestamp );
else $times[$hour_mins] = $hour_mins;
}
return $times;
}
Added index value as hour:
Here is the code:
<?php
$time_slot= array();
if ( empty( $format ) ) {
$format = 'H:i';
}
$lower = 0; $upper = 86400; $step = 3600; $format = '';
$i = 0;
foreach ( range( $lower, $upper, $step ) as $increment ) {
$increment = gmdate( 'H:i', $increment );
$time_slot[$i] = $increment;
$i++;
}
print_r($time_slot);
?>
Here is the result:
Array
(
[0] => 00:00
[1] => 01:00
[2] => 02:00
[3] => 03:00
[4] => 04:00
[5] => 05:00
[6] => 06:00
[7] => 07:00
[8] => 08:00
[9] => 09:00
[10] => 10:00
[11] => 11:00
[12] => 12:00
[13] => 13:00
[14] => 14:00
[15] => 15:00
[16] => 16:00
[17] => 17:00
[18] => 18:00
[19] => 19:00
[20] => 20:00
[21] => 21:00
[22] => 22:00
[23] => 23:00
[24] => 00:00
)
I needed a list of times like so in an array...
12am
12:30am
1:00pm
...
How can I do this with PHP?
Here's an improved version of Alex's function that uses seconds for more precision:
function hoursRange( $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[(string) $increment] = $date->format( $format );
}
return $times;
}
So, to make an array of times with 1-hour intervals over a 24-hour time period, use the defaults:
hoursRange();
Which will give you the following:
Array
(
[00:00] => 12:00 am
[01:00] => 1:00 am
[02:00] => 2:00 am
[03:00] => 3:00 am
[04:00] => 4:00 am
[05:00] => 5:00 am
[06:00] => 6:00 am
[07:00] => 7:00 am
[08:00] => 8:00 am
[09:00] => 9:00 am
[10:00] => 10:00 am
[11:00] => 11:00 am
[12:00] => 12:00 pm
[13:00] => 1:00 pm
[14:00] => 2:00 pm
[15:00] => 3:00 pm
[16:00] => 4:00 pm
[17:00] => 5:00 pm
[18:00] => 6:00 pm
[19:00] => 7:00 pm
[20:00] => 8:00 pm
[21:00] => 9:00 pm
[22:00] => 10:00 pm
[23:00] => 11:00 pm
)
Here are a few example uses:
// Every 15 Minutes, All Day Long
$range = hoursRange( 0, 86400, 60 * 15 );
// Every 30 Minutes from 8 AM - 5 PM, using Custom Time Format
$range = hoursRange( 28800, 61200, 60 * 30, 'h:i a' );
You can view a working snippet at CodePad.
Thank-you for reopening the question alex.
This is a solution that should resonate with functional programmers.
function halfHourTimes() {
$formatter = function ($time) {
if ($time % 3600 == 0) {
return date('ga', $time);
} else {
return date('g:ia', $time);
}
};
$halfHourSteps = range(0, 47*1800, 1800);
return array_map($formatter, $halfHourSteps);
}
I decided this one was better :)
function hoursRange($lower = 0, $upper = 23, $step = 1, $format = NULL) {
if ($format === NULL) {
$format = 'g:ia'; // 9:30pm
}
$times = array();
foreach(range($lower, $upper, $step) as $increment) {
$increment = number_format($increment, 2);
list($hour, $minutes) = explode('.', $increment);
$date = new DateTime($hour . ':' . $minutes * .6);
$times[(string) $increment] = $date->format($format);
}
return $times;
}
We can simply use strtotime to increment our time by N amount here in this case 30 minutes and date function to format it to our desired output.
$startTime = strtotime('12 am');
$endTime = strtotime('11:59 pm');
$arrInterval = [];
while($endTime >= $startTime){
$arrInterval[] = date("h:ia", $startTime);
$startTime = strtotime('+30 minutes', $startTime);
}
Here is my suggestion :
$start = new \DateTime('00:00');
$times = 24 * 2; // 24 hours * 30 mins in an hour
for ($i = 0; $i < $times-1; $i++) {
$result[] = $start->add(new \DateInterval('PT30M'))->format('H:i A');
}
print_r($result);
Hope this help.
This is maybe a more elegant way, but it requires the times to be in seconds (that also makes it more flexible).
function time_range( $start, $end, $step = 1800 ) {
$return = array();
for( $time = $start; $time <= $end; $time += $step )
$return[] = date( 'g:ia', $time );
return $return;
}
Simplest solution
$h = 0;
while ($h < 24) {
$key = date('H:i', strtotime(date('Y-m-d') . ' + ' . $h . ' hours'));
$value = date('h:i A', strtotime(date('Y-m-d') . ' + ' . $h . ' hours'));
$formatter[$key] = $value;
$h++;
}
Result are:
Array
(
[00:00] => 12:00 AM
[01:00] => 01:00 AM
[02:00] => 02:00 AM
[03:00] => 03:00 AM
[04:00] => 04:00 AM
[05:00] => 05:00 AM
[06:00] => 06:00 AM
[07:00] => 07:00 AM
[08:00] => 08:00 AM
[09:00] => 09:00 AM
[10:00] => 10:00 AM
[11:00] => 11:00 AM
[12:00] => 12:00 PM
[13:00] => 01:00 PM
[14:00] => 02:00 PM
[15:00] => 03:00 PM
[16:00] => 04:00 PM
[17:00] => 05:00 PM
[18:00] => 06:00 PM
[19:00] => 07:00 PM
[20:00] => 08:00 PM
[21:00] => 09:00 PM
[22:00] => 10:00 PM
[23:00] => 11:00 PM
)
Here's a more flexible version that doesn't need DateTime (since we're already working with timestamps in seconds anyway). ;-)
function get_hours_range( $start = 0, $end = 86400, $step = 3600, $format = 'g:i a' ) {
$times = array();
foreach ( range( $start, $end, $step ) as $timestamp ) {
$hour_mins = gmdate( 'H:i', $timestamp );
if ( ! empty( $format ) )
$times[$hour_mins] = gmdate( $format, $timestamp );
else $times[$hour_mins] = $hour_mins;
}
return $times;
}
Added index value as hour:
Here is the code:
<?php
$time_slot= array();
if ( empty( $format ) ) {
$format = 'H:i';
}
$lower = 0; $upper = 86400; $step = 3600; $format = '';
$i = 0;
foreach ( range( $lower, $upper, $step ) as $increment ) {
$increment = gmdate( 'H:i', $increment );
$time_slot[$i] = $increment;
$i++;
}
print_r($time_slot);
?>
Here is the result:
Array
(
[0] => 00:00
[1] => 01:00
[2] => 02:00
[3] => 03:00
[4] => 04:00
[5] => 05:00
[6] => 06:00
[7] => 07:00
[8] => 08:00
[9] => 09:00
[10] => 10:00
[11] => 11:00
[12] => 12:00
[13] => 13:00
[14] => 14:00
[15] => 15:00
[16] => 16:00
[17] => 17:00
[18] => 18:00
[19] => 19:00
[20] => 20:00
[21] => 21:00
[22] => 22:00
[23] => 23:00
[24] => 00:00
)
If I have two dates 20-4-2010 and 22-4-2010
in two text box and
I want the dates to be like this 20, 21, 22. How do I get that ?
I am pretty sure this has been answered a quadrillion times before, but anyway:
$start = strtotime('20-04-2010 10:00');
$end = strtotime('22-04-2010 10:00');
for($current = $start; $current <= $end; $current += 86400) {
echo date('d-m-Y', $current);
}
The 10:00 part is to prevent the code to skip or repeat a day due to daylight saving time.
By giving the number of days:
for($i = 0; $i <= 2; $i++) {
echo date('d-m-Y', strtotime("20-04-2010 +$i days"));
}
With PHP5.3
$period = new DatePeriod(
new DateTime('20-04-2010'),
DateInterval::createFromDateString('+1 day'),
new DateTime('23-04-2010') // or pass in just the no of days: 2
);
foreach ( $period as $dt ) {
echo $dt->format( 'd-m-Y' );
}
You can use mktime().
mktime() is useful for doing date arithmetic and validation, as it will automatically calculate the correct value for out-of-range input.
If you increment the day number you get a valid date back, even if you go past the end of the month:
<?php
$day= 25;
$dateEnd = mktime(0,0,0,5,3,2010);
do {
$dateCur = mktime(0,0,0,4,$day,2010);
$day++;
print date( 'd-m-y', $dateCur) .'<br>';
} while ($dateCur < $dateEnd);
Output:
25-04-10
26-04-10
27-04-10
28-04-10
29-04-10
30-04-10
01-05-10
02-05-10
03-05-10
You can do:
$start = strtotime("2010-04-20"); // get timestamp for start date.
$end = strtotime("2010-04-22"); // get timestamp for end date.
// go from start timestamp to end timestamp adding # of sec in a day.
for($t=$start;$t<=$end;$t+=86400) {
// get the date for this timestamp.
$d = getdate($t);
// print the date.
echo $d['mday'].'-'.$d['mon'].'-'.$d['year']."\n";
}
Output:
20-4-2010
21-4-2010
22-4-2010
/**
* Function to list of weeks start and end.
* #param string strDateFrom (Date From "YYYY-MM-DD")
* #param string strDateTo (Date To "YYYY-MM-DD")
* #return array weeks
*/
function getWeeksBetweenTowDates($date_from, $date_to) {
$startweek = $current_week = date("W", strtotime($date_from));
$endweek = date("W", strtotime($date_to));
$current_year = date("Y", strtotime($date_from));
$current_yearweek = date("Y", strtotime($date_from)) . $startweek;
$end_yearweek = date("Y", strtotime($date_to)) . $endweek;
$start_day = 0;
$end_day = 0;
while ($current_yearweek <= $end_yearweek) {
$dto = new DateTime();
if ($start_day == 0) {
$start_day = $dto->setISODate(date("Y", strtotime($date_from)), $current_week, 0)->format('Y-m-d');
$end_day = $dto->setISODate(date("Y", strtotime($date_from)), $current_week, 6)->format('Y-m-d');
} else {
$start_day = $dto->setISODate(date("Y", strtotime($end_day)), $current_week, 0)->format('Y-m-d');
$end_day = $dto->setISODate(date("Y", strtotime($end_day)), $current_week, 6)->format('Y-m-d');
}
$arr_weeks[sprintf("%02d", $current_week)] = $start_day . " =>" . $end_day;
$last_yearweek_in_year = $current_year . date("W", strtotime('31-12-' . $current_year));
if ($current_yearweek == $last_yearweek_in_year) { //last week in the year
$current_week = 1;
$current_year = ($current_year + 1);
} else {
$current_week = ($current_week + 1);
}
$current_yearweek = $current_year . sprintf("%02d", $current_week);
}
return $arr_weeks;
}
Run Like : date_from=2015-10-20 , date_to=2016-04-15
$arr_weeks = $this->getWeeksBetweenTowDates($date_from, $date_to);
Output:
Array
(
[43] => 2015-10-18 =>2015-10-24
[44] => 2015-10-25 =>2015-10-31
[45] => 2015-11-01 =>2015-11-07
[46] => 2015-11-08 =>2015-11-14
[47] => 2015-11-15 =>2015-11-21
[48] => 2015-11-22 =>2015-11-28
[49] => 2015-11-29 =>2015-12-05
[50] => 2015-12-06 =>2015-12-12
[51] => 2015-12-13 =>2015-12-19
[52] => 2015-12-20 =>2015-12-26
[53] => 2015-12-27 =>2016-01-02
[01] => 2016-01-03 =>2016-01-09
[02] => 2016-01-10 =>2016-01-16
[03] => 2016-01-17 =>2016-01-23
[04] => 2016-01-24 =>2016-01-30
[05] => 2016-01-31 =>2016-02-06
[06] => 2016-02-07 =>2016-02-13
[07] => 2016-02-14 =>2016-02-20
[08] => 2016-02-21 =>2016-02-27
[09] => 2016-02-28 =>2016-03-05
[10] => 2016-03-06 =>2016-03-12
[11] => 2016-03-13 =>2016-03-19
[12] => 2016-03-20 =>2016-03-26
[13] => 2016-03-27 =>2016-04-02
[14] => 2016-04-03 =>2016-04-09
[15] => 2016-04-10 =>2016-04-16
)
Try this, Hope it help helps
$begin = date("Y-m-d", strtotime($date);
$end = date("Y-m-d", strtotime($date));
$begin = new DateTime($begin);
$end = new DateTime($end);
for ($i = $begin; $i <= $end; $i=$i->modify('+1 day')) {
echo $i->format('Y-m-d');
}