loop over start-end time add minutes with next day - php

I am trying to add 15 minutes to given times till the end time is reached. I have been looking at loop over the time till it reaches end time with specific interval but this solution helps only for times within the same day.
In case as shown below it will not work.
$startTime = '16:00';
$endTime = '02:00';
The output I am looking for is as follow:
16:00
16:15
16:30
16:45
17:00
17:15
17...
.....
01:45
02:00
And let's say it is now 16:13 how can I then start the output from 16:30? or even better 30 mins later for example, at 16:45.
Any help is appreciated.

I think the next solution can help:
<?php
// get current time and round it to next half hour
$start = (intdiv(time(),(30 * 60)) + 1) * (30*60);
// since intdiv introduced in PHP 7 in previous PHP versoins
// intval() function can be used instead
$start = (intval(time()/(30 * 60)) + 1) * (30*60);
$end = strtotime('02:00');
// if end time less then start add one day
if ($end < $start) $end += 60 * 60 * 24;
while ($start <= $end) {
echo date('H:i',$start) . PHP_EOL;
// Increment Start date
$start += (15*60);
}
share PHP code

Related

Substract Time Logic - PHP

I want to show time slots between 2 times. Start time & End time. Used below code, it's working fine. It loops start and end time and add 30 mins to time. Starts from 2:00pm, 2:30pm, 3:00pm all the way till 10:00pm
$start_time = "14:00:00";
$end_time = "22:30:00";
#for ($i = strtotime($start_time); $i < strtotime($end_time); $i=$i+1800)
<li data-time="{{date('g:i A', $i)}}" class="timefield">{{date("g:i A", $i)}}</li>
#endfor
What I am stuck on is 2 parts
Hide past time, lets say right now is 4:00pm, it should hide past time slots i-e 2:00pm,2:30pm,:3:00pm,3:30pm
If right now is 4:00pm, it should start from 5:00pm all the way till 10:00pm. Adding extra buffer time of 1 hour.
You could insert the current timestamp in your logic like this:
$start_time = strtotime("14:00:00");
$end_time = strtotime("22:30:00");
$now = (new DateTime())->getTimestamp();
$nowRemaining = $now % 1800; // Divide to half hours & get the remaining seconds
$nowRounded = $now - $nowRemaining; // Round to half hours
$nextHour = $nowRounded + ($nowRemaining == 0 ? 3600 : 5400); // Add the extra buffer
for ($i = max($start_time, $nextHour); $i < $end_time; $i=$i+1800) {
...
}

How to find at what time activity finished?

I have activity start time and and total hour i just want to find the end time of that activity i mean time when activity finished ?
for example I start my activity
for
$hour = 24:60:08 // 24 hour 60 min 8 min total hour
$starttime = 13:09 // using 24 hour format it 01:09
//means activity start at = 13:09
$endtime = ?
I want to find out the the time finished time of an activity
Thanks
You can with adding to time exploded hour like following:
$hour = '24:60:08';
$starttime = '13:09';
$times = explode(':', $hour);
$timestamp = strtotime($starttime) + ($times[0] * 3600 + $times[1] * 60 + $times[2]);
$endtime = date('H:i', $timestamp);
echo $endtime; // 14:09
Explain:
24 = 24(hours) * 60(mins) * 60(secs)
60 = 60(mins) * 60(secs)
08 = 8(sec)
It appears like you have a start time of an activity and then a duration of how long it ran and you want to compute what's the end time. Your question becomes unclear by your use of non descriptive variable names nor any comments. You can do
<?php
$duration = "25:00:08";
$starttime = "13:09";
list($hours,$minutes,$seconds) = explode(":",$duration);
$totalTime = $seconds+($minutes*60)+($hours*3600);
$endTime = date("h:i",strtotime($starttime)+$totalTime);
echo $endTime;
?>
Sidenote: 24:60:08, 60 minutes is nothing. That's 25 hours 0 minutes and 8 seconds
If you want to get the time elapsed to process something, let's say to execute a function, you can easily do it with PHP microtime.
Assume you want to find time elapsed to execute function test, here how you do this.
public function test()
{
$time_start = microtime(true);
/*
Your code
goes here
*/
$time_end = microtime(true);
$execution_time = (($time_end - $time_start) / 60) * 60;
echo $execution_time; //This will show you the execution time in seconds.
}
If you want, you can add this seconds to any previous time stamp you saved, in order to get the execution terminated time in hh:mm:ss format. Hope this helps.
Cheers!
I am unable to understand exactly what you are looking for
<?php
$hour = "24:60:08"; // 24 hour 60 min 8 min total hour
$starttime = "13:09";
$hourArray=explode(":", $hour);
$starttimeArray=explode(":", $starttime);
$endtimearray=array();
for ($i=0;$i<3;$i++){
//Verifyng time is set else making it zero
if (!isset($hourArray[$i]))
$hourArray[$i]=0;
if (!isset($starttimeArray[$i]))
$starttimeArray[$i]=0;
$endtimearray[$i]=$hourArray[$i]-$starttimeArray[$i];
}
echo $endtimearray[0];
for ($i=1;$i<3;$i++)
echo ":$endtimearray[$i]";
Hopefully This is what you are looking for.

Midnight time issue

I am having problem detecting if the shop is still open or closed after midnight.
On Tuesday ($weekday = 2), shop open from 6 PM to 1:30 AM (after midnight)
Assume current time is 01:05 AM
$weekday = 2;
//Convert current time to minutes (01:05)
$currentTime = ($weekday - 1) * 1440 + "01" * 60 + "05";
//Current Week Day
$shopOpenTime = "18:00";
$shopCloseTime = "01:30";
$open = explode(':', $shopOpenTime);
$close = explode(':', $shopCloseTime);
//Convert to Minutes;
$MinutesOpen = (($weekday - 1) * 1440) + ($open[0] * 60 + $open[1]);
$MinutesClose = (($weekday - 1) * 1440) + ($close[0] * 60 + $close[1]);
if ($MinutesClose < $MinutesOpen)
$MinutesClose += 60 * 24;
if (($currentTime >= $MinutesOpen) && ($currentTime < $MinutesClose)) {
echo "Shop Is Open";
} else {
echo "Shop Is Close";
}
What is the solution to fix this issue?
Honestly this entire chunk of code should be re-written. The logic is doomed because your $weekday parameter is comparing the same day for $currentTime as $minutesOpen. You added 24 hours to $minutesClose to push it to (technically Wed), now that comparison is correct. It says Closed because you haven't moved $currentTime up 24 hours into wed.
So if you were to just read this in english you're comparing 1:30am on Tuesday (which is right after monday night) against 6:30 pm on Tuesday, and this fails (this is because of the $weekday parameter is set to tuesday in the $currentTime).
Without seeing how you populate your $weekday parameter, I'm guessing that when you actually run this code being poplated with say the date() function, at 12:01 (on tuesday) it's going to increment to wed, then you're code will be populating open and close time with wed's hours, which is going to be off too.
I'm sorry I know this isn't a solution saying to re-write the entire logic, but it's going to be massively flawed in a production environment.
If you just want to make it work, staying with the mindset/context of 'tuesday' you have to reflect current time in tuesday's sense, and thats with 25:05 meaning 1:05 on wed, and not 01:05 tuesday for the second time. That keeps the context correct and it works.
$currentTime = ($weekday - 1) * 1440 + "25" * 60 + "05";
You are comparing the current time to the opening period that will begin on the current time's day. But the shop is currently open due to an opening period that started yesterday. Just compare with yesterday's period also:
if ((($currentTime >= $MinutesOpen - 1440) && ($currentTime < $MinutesClose - 1440)) || (($currentTime >= $MinutesOpen) && ($currentTime < $MinutesClose))) {
But beware, this works only, if the shop opens / closes every day at the same time.

Converting user's day and time to server's day and time in php

I have a scenario in which the user selects a time and day (or multiple days) and that value must be converted to whatever that day and time would be in UTC time. I have the gmt offset amount for each user (the users set it when they signup). For instance:
A user in the eastern timezone selects:
3:15 pm, Monday, Tuesday, Friday
I need to know what time and days that information would be in UTC time. The solution has to take into situations such Monday in one timezone can be a different day in UTC time. Also, if the time can be converted to 24 hour format, that would be a plus.
For the sake of clarity, something along the lines of an array should be returned such as:
Array('<3:15 pm eastern adjusted for utc>', '<Monday adjusted for UTC>', '<Tuesday adjusted for UTC>', '<Friday adjusted for UTC>');
I don't need the result to be directly formatted into an array like that - that's just the end goal.
I am guessing it involves using strtotime, but I just can't quite my finger out how to go about it.
$timestamp = strtotime($input_time) + 3600*$time_adjustment;
The result will be a timestamp, here's an example:
$input_time = "3:15PM 14th March";
$time_adjustment = +3;
$timestamp = strtotime($input_time) + 3600*$time_adjustment;
echo date("H:i:s l jS F", $timestamp);
// 16:15:00 Monday 14th March
EDIT: kept forgetting little things, that should be working perfectly now.
Made a function to do the job:
<?
/*
* The function week_times() converts a a time and a set of days into an array of week times. Week times are how many seconds into the week
* the given time is. The $offset arguement is the users offset from GMT time, which will serve as the approximation to their
* offset from UTC time
*/
// If server time is not already set for UTC, uncomment the following line
//date_default_timezone_set('UTC');
function week_times($hours, $minutes, $days, $offset)
{
$timeUTC = time(); // Retrieve server time
$hours += $offset; // Add offset to user time to make it UTC time
if($hours > 24) // Time is more than than 24 hours. Increment all days by 1
{
$dayOffset = 1;
$hours -= 24; // Find out what the equivelant time would be for the next day
}
else if($hours < 0) // Time is less than 0 hours. Decrement all days by 1
{
$dayOffset = -1;
$hours += 24; // Find out what the equivelant time would be for the prior day
}
$return = Array(); // Times to return
foreach($days as $k => $v) // Iterate through each day and find out the week time
{
$days[$k] += $dayOffset;
// Ensure that day has a value from 0 - 6 (0 = Sunday, 1 = Monday, .... 6 = Saturday)
if($days[$k] > 6) { $days[$k] = 0; } else if($days[$k] < 0) { $days[$k] = 6; }
$days[$k] *= 1440; // Find out how many minutes into the week this day is
$days[$k] += ($hours*60) + $minutes; // Find out how many minutes into the day this time is
}
return $days;
}
?>

PHP : How to calculate the remaining time in minutes?

Suppose the target time is 4.30 pm and the current time is 3.25 pm , how will i calculate the minutes remaining to reach the target time ? I need the result in minutes.
session_start();
$m=30;
//unset($_SESSION['starttime']);
if(!$_SESSION['starttime']){
$_SESSION['starttime']=date('Y-m-d h:i:s');
}
$stime=strtotime($_SESSION['starttime']);
$ttime=strtotime((date('Y-m-d h:i:s',strtotime("+$m minutes"))));-->Here I want to calcuate the target time; the time is session + 30 minutes. How will i do that
echo round(abs($ttime-$stime)/60);
Krishnik
A quick calculation of the difference between two times can be done like this:
$start = strtotime("4:30");
$stop = strtotime("6:30");
$diff = ($stop - $start); //Diff in seconds
echo $diff/3600; //Return 2 hours. Divide by something else to get in mins etc.
Edit*
Might as well add the answer to your problem too:
$start = strtotime("3:25");
$stop = strtotime("4:30");
$diff = ($stop - $start);
echo $diff/60; //Echoes 65 min
Oh and one more edit:) If the times are diffent dates, like start is 23:45 one day and end is 0:30 the next you need to add a date too to the strtotime.

Categories