laravel 5.6 start time end time duration - php

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.

$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];
}

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

Related

PHP Range of Times

I need a list of times that will be used for collection times. The user will select when collections starts, ends and the intervals between these times.
If i set:
Start: 11:00
End: 20:00
Interval: 30
It will correctly produce a list from 11:00 to 20:00 with 30 minute intervals between... eg 11:00, 11:30, 12:00, ... 19.00, 19.30, 20.00
Now for the issue, if i set:
Start: 20:00
End: 03:00
Interval: 30
The following list it produced, the times are going backwards, going down from 8pm to 3am, when it should be going up! 20:00, 19:30, 19:00, ... 04.00, 03.30, 03.00
How can i adapt my code so that it always goes up? so it produces these results instead... 20:00, 20:30, 21:00, ... 02.00, 02.30, 03.00
Heres my code:
$collectTimes = array();
$range = range(strtotime($settingsCTS), strtotime($settingsCTE), $settingsCTI * 60);
foreach ($range as $time) {
$collectTimes[] = date("H:i", $time);
}
$startTime = strtotime('20:00');
$endTime = strtotime('03:00');
$interval = 30;
if ($endTime < $startTime) {
$endTime += 60 * 60 * 24;
}
$collectTimes = array();
$range = range($startTime, $endTime, $interval * 60);
foreach ($range as $time) {
$collectTimes[] = date("H:i", $time);
}
I think the code is self-explanatory, I really have nothing smart to say about it :)
$start = "20:00";
$end = "03:00";
$interval = 30;
$temp = null;
$intervals = [date("H:i",strtotime($start))];
while ( $temp !== date("H:i",strtotime($end)) ) {
$temp = date("H:i",strtotime($start." + $interval minutes"));
array_push($intervals,$temp);
$interval += 30;
}

PHP show range of hours and ignore past time

I am trying to make a little script which shows range of hours between 11:00 and 17:00. 11:00 is start point and 17:00 is end point. So far i have made this:
<?php
// Defining hours
$now = "13:00"; // <- my time now
$start_time = "11:00"; // start point
$end_time = "17:00"; // end point
// Convert to timestamps
$begin = strtotime($start_time);
$end = strtotime($end_time);
// Display range
while($begin <= $end) {
echo date("H:i", $begin)." </br />";
$begin = strtotime('1 hour', $begin);
}
?>
And it successfully output of range between start and end points:
11:00
12:00
13:00
14:00
15:00
16:00
17:00
My goal is to make this script show range of hours from 13:00 (my time) if actual time is more than start time (11:00). Something like this:
11:00 hidden
12:00 hidden
13:00
14:00
15:00
16:00
17:00
Can someone suggest how to make it?
In this case simply use this:
$present = strtotime($now);
if($present > $begin){
$begin = $present;
}
but what you need if say $now = 18:00 or beyond this.
In this case this code show nothing.
I think you can simplify your whole solution. Instead of using time operations, why don't you simply increase a variable from current hour or 11 to 17. To determine $begin simply use max(), like this:
$begin = max(date('H'), 11);
$end = 17;
while($begin <= $end) {
echo $begin . ':00<br>';
$begin++;
}
I have added small bits as #user1234 suggested and now it works as i wanted. Here is the full code for reference to others.
<?php
// Defining hours
$now = "13:00"; // <- my time now
$start_time = "11:00"; // start point
$end_time = "17:00"; // end point
// Convert to timestamps
$actual = strtotime($now);
$begin = strtotime($start_time);
$end = strtotime($end_time);
// Added this to see if actual time is more than start time - creadit user1234
if($actual > $begin) {
$begin = $actual;
}
// Added this to see if actual time is more than 17:00
if($actual > $end) {
echo "Try tomorrow";
}
// Display ranges accordingly.
while($begin <= $end) {
echo date("H:i", $begin)." </br />";
$begin = strtotime('1 hour', $begin);
}
?>
Anyone is welcome to test and use if needed.

PHP - Calculating working hours between two dates but exclude the time when request is on hold

Can some one help me write a function that calculates the number of working hours between two dates but want to exclude the time when the request had a status of "On Hold".
So lets say the request came in at 3PM friday and was closed at 3PM Wednesday, and working hours are from 8AM to 5PM pacific (Mon thru Friday)...Total working hours will be 27 hours...but if the request remained on hold from Monday 3PM till Tuesday 3PM...Actual work time on the request really becomes 18 hours instead of 27 hours.
I have recently started working on PHP and have been assigned this task which is very confusing to me. Please help
All you have to do is get the total time elapsed, then substract the non-working hours.
You can use dateTime and datePeriod php objects for that (requires php 5.3)
Here a small script to do what you want (but you will have probably to adapt for your needs)
<?php
ini_set('display_errors', 'on');
define('DAY_WORK', 32400); // 9 * 60 * 60
define('HOUR_START_DAY', '08:00:00');
define('HOUR_END_DAY', '17:00:00');
// get begin and end dates of the full period
$date_begin = '2013-11-29 15:00:00';
$date_end = '2013-12-03 15:00:00';
// keep the initial dates for later use
$d1 = new DateTime($date_begin);
$d2 = new DateTime($date_end);
// and get the datePeriod from the 1st to the last day
$period_start = new DateTime($d1->format('Y-m-d 00:00:00'));
$period_end = new DateTime($d2->format('Y-m-d 23:59:59'));
$interval = new DateInterval('P1D');
//$interval = new DateInterval('weekdays'); // 1 day interval to get all days between the period
$period = new DatePeriod($period_start, $interval, $period_end);
$worked_time = 0;
$nb = 0;
// for every worked day, add the hours you want
foreach($period as $date){
$week_day = $date->format('w'); // 0 (for Sunday) through 6 (for Saturday)
if (!in_array($week_day,array(0, 6)))
{
// if this is the first day or the last dy, you have to count only the worked hours
if ($date->format('Y-m-d') == $d1->format('Y-m-d'))
{
$end_of_day_format = $date->format('Y-m-d '.HOUR_END_DAY);
$d1_format = $d1->format('Y-m-d H:i:s');
$end_of_day = new DateTime($end_of_day_format);
$diff = $end_of_day->diff($d1)->format("%H:%I:%S");
$diff = split(':', $diff);
$diff = $diff[0]*3600 + $diff[1]*60 + $diff[0];
$worked_time += $diff;
}
else if ($date->format('Y-m-d') == $d2->format('Y-m-d'))
{
$start_of_day = new DateTime($date->format('Y-m-d '.HOUR_START_DAY));
$d2_format = $d2->format('Y-m-d H:i:s');
$end_of_day = new DateTime($end_of_day_format);
$diff = $start_of_day->diff($d2)->format('%H:%I:%S');
$diff = split(':', $diff);
$diff = $diff[0]*3600 + $diff[1]*60 + $diff[0];
$worked_time += $diff;
}
else
{
// otherwise, just count the full day of work
$worked_time += DAY_WORK;
}
}
if ($nb> 10)
die("die ".$nb);
}
echo sprintf('Works from %s to %s, You worked %d hour(s)', $date_begin, $date_end, $worked_time/60/60);
Calculate work time with an accuracy of 1 minute.
WARNING: This function can take many seconds to load as it does a loop for every minute between the time span.
<?php
$request = array(
'start' => '3PM Nov 29 2013',
'end' => '3PM Dec 4 2013'
);
echo calculate_work($request);
/**
* Calculate work time by looping through every minute
* #param array $request start to end time
* #return int work time in minutes
*/
function calculate_work($request)
{
$start = strtotime($request['start']);
$end = strtotime($request['end']);
$work_time = 0;
/* Add 1 minute to the start so that we don't count 0 as a minute */
for ($time = $start + 60; $time <= $end; $time += 60)
{
// Weekends
if (date('D', $time) == 'Sat' OR date('D', $time) == 'Sun')
continue;
// Non Working Hours
if (date('Hi', $time) <= '0800' OR date('Hi', $time) > '1700')
continue;
// On Hold
if ($time > strtotime('3PM Dec 2 2013') AND $time <= strtotime('3PM Dec 3 2013'))
continue;
$work_time++;
}
// Divide by 60 to turn minutes into hours
return $work_time / 60;
}
/**
* Get the total working hours in seconds between 2 dates..
* #param DateTime $start Start Date and Time
* #param DateTime $end Finish Date and Time
* #param array $working_hours office hours for each weekday (0 Monday, 6 Sunday), Each day must be an array containing a start/finish time in seconds since midnight.
* #return integer
* #link https://github.com/RCrowt/working-hours-calculator
*/
function getWorkingHoursInSeconds(DateTime $start, DateTime $end, array $working_hours)
{
$seconds = 0; // Total working seconds
// Calculate the Start Date (Midnight) and Time (Seconds into day) as Integers.
$start_date = clone $start;
$start_date = $start_date->setTime(0, 0, 0)->getTimestamp();
$start_time = $start->getTimestamp() - $start_date;
// Calculate the Finish Date (Midnight) and Time (Seconds into day) as Integers.
$end_date = clone $end;
$end_date = $end_date->setTime(0, 0, 0)->getTimestamp();
$end_time = $end->getTimestamp() - $end_date;
// For each Day
for ($today = $start_date; $today <= $end_date; $today += 86400) {
// Get the current Weekday.
$today_weekday = date('w', $today);
// Skip to next day if no hours set for weekday.
if (!isset($working_hours[$today_weekday][0]) || !isset($working_hours[$today_weekday][1])) continue;
// Set the office hours start/finish.
$today_start = $working_hours[$today_weekday][0];
$today_end = $working_hours[$today_weekday][1];
// Adjust Start/Finish times on Start/Finish Day.
if ($today === $start_date) $today_start = min($today_end, max($today_start, $start_time));
if ($today === $end_date) $today_end = max($today_start, min($today_end, $end_time));
// Add to total seconds.
$seconds += $today_end - $today_start;
}
return gmdate("H:i:s", $seconds);
}

Setting a time and date and adding to it in PHP

Basically am trying to set a time and a date in PHP then set a time gap which will range between minutes, loop through between a start time and end time echoing something out for each one. Have tried loads of different ways and cant seem to figure a way to set a date and add to it.
This seems the best script I have modified so far:
$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');
$newendtime = $endtime->format('Y-m-d H:i');
$timedate = new DateTime('2012-01-01 09:00');
while($stamp < $newendtime)
{
$time = new DateTime($timedate);
$time->add(new DateInterval('PT' . $minutes . 'M'));
$timedate = $time->format('Y-m-d H:i');
echo $timedate;
}
$minutes = 5;
$endtime = new DateTime('2012-01-01 09:00');
//modified the start value to get something _before_ the endtime:
$time = new DateTime('2012-01-01 8:00');
$interval = new DateInterval('PT' . $minutes . 'M');
while($time < $endtime){
$time->add($interval);
echo $time->format('Y-m-d H:i');
}
Do everything in seconds, and use php's time(), date(), and mktime functions.
In UNIX Time, dates are stored as the number of seconds since Jan 1, 1970.
You can render UNIX Timestamps with date().
$time = time(); // gets current time
$endtime = mktime(0,0,0, 1, 31, 2012); // set jan 31 # midnight as end time
$interval = 60 * 5; // 300 seconds = 5 minutes
while($time < $endtime){
$time += $interval;
echo date("M jS Y h:i:s a",$time) . "<br>"; // echos time as Jan 17th, 2012 1:04:56 pm
}
date reference:
http://us3.php.net/manual/en/function.date.php (includes superb date format reference too)
mktime reference: http://us2.php.net/mktime
time() only gets the current time, but just for kicks n' giggles: http://us2.php.net/time
And, it's super easy to store in a database!
This function will let you add date to your existing datetime. This will also preserves HH:MM:SS
<?php
function add_date($givendate,$day=0,$mth=0,$yr=0) {
$cd = strtotime($givendate);
$newdate = date('Y-m-d h:i:s', mktime(date('h',$cd),
date('i',$cd), date('s',$cd), date('m',$cd)+$mth,
date('d',$cd)+$day, date('Y',$cd)+$yr));
return $newdate;
}
?>
Usage:
add_date($date,12,0,0);
where $date is your date.

How to retrieve an array of each date within two epochs

I have two epochs. I want to figure out all the dates that are valid within the two epochs.
For example, if I have the epochs 946684800 (Sat, 01 Jan 2000 00:00:00 GMT) and 947203200 (Fri, 07 Jan 2000 00:00:00 GMT), I want to be able to get: 01/01/2000, 02/01/2000, 03/01/2000, 04/01/2000, etc.
If you have PHP 5.3 or newer, you could do this:
$date1 = new DateTime;
$date1->setTimestamp(946684800);
$date2 = new DateTime;
$date2->setTimestamp(947203200);
$interval = new DateInterval('P1D');
while ( $date1 <= $date2 )
{
$dates_in_between[] = $date1->getTimestamp();
$date1->add($interval);
}
Alternatively, you could use this:
// 1 day = 60 seconds * 60 minutes * 24 hours = 86400
for ($date = 946684800; $date <= 947203200; $date += 86400)
$dates_in_beteween[] = $date;
$dates_in_between will contain a list of "dates" in between.
PHP time values are just Unix timestamps - seconds since Jan 1/1970. Going off PHP 5's datetime object:
$start = strtotime('01 Jan 2000');
$end = strtotime('07 Jan 2000');
for ($d = $start; $d <= $end; $d += 86400) { // increment by 86,400 seconds, aka 1 day
echo date('d/m/Y', $d);
}
There's better ways of going about it, using the DateTime / DateInterval objects, but this is just to show the basics.
Given that your epoch is in seconds you could always add the number of seconds found in a day to the first epoch:
946684800 + 86400 = 946771200 -> Sun, 02 Jan 2000 00:00:00 GMT
And go on like this, I explain better:
947203200 - 946684800 = 518400 / 86400 = 6 (exactly 6 days)
so (PSEUDOCODE):
for(int i = 946684800; i<946684800 ;i+=86400){
day = getDate(i);
}
$epoch1 = '946684800';
$epoch2 = '947203200';
$i = 0;
while($time < $epoch2) {
$time = mktime(0, 0, 0, date("m", $epoch1) , date("d", $epoch1)+$i, date("Y",$epoch1));
echo date('d/m/Y', $time)."<br>";
$i++;
}
If understanding the question right, you want every DAY within the 2 epochs (2000-01-01 and 2000-01-07)..
Can be done like so:
<?php
$epoch1 = 946684800;
$epoch2 = 947203200;
$difference = $epoch1 - $epoch2;
..
//count days
$amountOfDays = round(($epoch2-$epoch1)/86400);
//looping all days
for($i=1; $i<=$amountOfDays; $i++) {
echo date('d/m/Y', $epoch1+($i*86400);
}
?>
$start = strtotime('2011-06-01');
$end = strtotime('2011-06-15');
$date = $start;
$anArray = array();
while ($date <= $end) {
$date = strtotime("+1 DAY", $date);
$anArray[] = $date;
}

Categories