Laravel Carbon - How to add minutes - php

I have a form where I ask 4 hours, It's morning start and end hour and the same for afternoon.
I'm using Carbon but it returns me 0 if I put 30 minutes, it rounds to down.
I try with diffInHours and diffInMinutes but it rounds always down in both ways.
This is my code example:
$startTime1 = Carbon::createFromFormat('H:s', '09:00');
$startTime2 = Carbon::createFromFormat('H:s', '10:30');
$startTime3 = Carbon::createFromFormat('H:s', '14:00');
$startTime4 = Carbon::createFromFormat('H:s', '16:00');
$morningTime = $startTime2->diffInHours($startTime1);
$afternoonTime = $startTime4->diffInHours($startTime3);
$total = $morningTime + $afternoonTime;
In $morningTime it returns 1 and should return 1,30.
In $afternoonTime it returns 2 and it's correct.
If I use with diffInMinutes it put 60 in $morningTime and 120 in $afternoonTime. It's wrong again in morning time.
How can I solve that?
Thank you

You are assigning seconds H:s in the Carbon format, use H:i:
$startTime1 = Carbon::createFromFormat('H:i', '10:30');
And You can use format() method to format the difference in time
$morningTime = $startTime2->diff($startTime1)->format('%H:%I');
Edit: there is no way to combine dateInterval instance, but you still can use timestamp:
$total_in_seconds = ($startTime2->timestamp - $startTime1->timestamp) + ($startTime4->timestamp - $startTime3->timestamp);
$total = Carbon::createFromTimestamp($total_in_seconds)->format('h:i');

Related

Carbon count minutes from timestamp

I am working with the PHP Carbon library. And I am trying to get the total time in minutes from a timestamp.
$time = new Carbon('02:13:23');
And I was wondering if there is a function like countMinutes() or totalMinutes() that would return in this case 133.38 which is 2 hours + 13 min + 23 sec. = 133.38
Or do I have to do it myself without the help of the library .. 120+13+(23/60)
Try the below code :
$time = Carbon::createFromTimeString('02:13:23');
$start_of_day = Carbon::createFromTimeString('02:13:23')->startOfDay();
$total_minutes = $time->diffInMinutes($start_of_day);
dd($time,$start_of_day,$total_minutes);
Here is a solution for getting minutes from a Carbon object.
// Create Carbon object from a specific date
$time = Carbon::createFromFormat('H:i:s', '02:13:23');
// Get days, hours and then minutes
$days = $startDate->diffInDays($time);
$hours = $startDate->copy()->addDays($days)->diffInHours($time);
$minutes = $startDate->copy()->addDays($days)->addHours($hours)->diffInMinutes($time);
echo $minutes;
Check the Carbon's documentation, there is a lot of good examples to get started.
Good luck!

PHP: Wrong Time Calculation

I am working on a project and writing a function to add two different times. The times are stored in database as a string.
I'm:
Pulling value from db
converting it into time using strtotime
adding times using date function
Here is my code:
$time_1 = '1:00';
$time_2 = '0:05';
//should be 1:05, whereas it prints 04:05
echo date("H:i", strtotime($time_1) + strtotime($time_2));
Please tell me, what is wrong with above code and how it can be fixed?
Thanks
Your problem is because strtotime returns the number of seconds since the Unix Epoch (Jan 1 1970). So what you are getting is not values of 60 and 5, but something more like 1537570800 and 1537567500. When you add those two values together, you end up with a date far in the future, with what looks effectively like a random time. To compensate for this, you need to subtract the value of strtotime at the start of the day to make the second time a relative time e.g.:
echo date("H:i", strtotime($time_1) + strtotime($time_2) - strtotime('00:00'));
Output:
01:05
Update
Since it turns out that the sum of the two times can exceed 24 hours, the above code will not work (the maximum time it will display is 23:59 before rolling over to 00:00. So it is necessary to convert both times to a relative number of minutes to the start of the day, add them and then display as hours and minutes:
$time_1 = '12:00';
$time_2 = '14:30';
$time_sum = (strtotime($time_1) + strtotime($time_2) - 2 * strtotime('00:00')) / 60;
printf('%02d:%02d', intdiv($time_sum, 60), $time_sum % 60);
Output:
26:30
Use DateTime::createFromFormat function, and taking ideas from Adding two DateTime objects in php
$time_1 = '1:00';
$time_2 = '0:05';
$t1 = DateTime::createFromFormat('G:i', $time_1);
$t2 = DateTime::createFromFormat('G:i', $time_2);
$interval1 = $t1->diff(new DateTime('00:00:00')) ;
$interval2 = $t2->diff(new DateTime('00:00:00')) ;
$e = new DateTime('00:00');
$f = clone $e;
$e->add($interval1);
$e->add($interval2);
$total = $f->diff($e)->format("%H:%I:%S");
Additional Details:
G and H 24-hour format of an hour with or without leading zeros
i Minutes with leading zeros 00 to 59

PHP Get Time From X Percentage of Total Time

I don't know if this will make sense but I would like to get the time from percentage of a value, I have the following as an input example:
mypercentage = 50;
mytime = "00:59:59"
As you can see, my time is 60 minutes (1 hour) and 50% of that is 30 minutes therefore from the 2 above inputs I would like to get the following output
(50 % of an hour):
00:30:00
Explode the string into an array
Convert the 3 elements into numbers
Find the value in seconds. $array[0]*3600+$array[1]*60+$array[2]
Calculate the time from the value in step 3 and the percentage.
Use /3600 and /60 to find the hour and minutes and %60 to find the seconds.
put the values in an array and implode to a string, or just use
$hour.":".$minute.":".$second
Thank you all who responded, I found this solution to work:
$mypercentage = 50;
$mytime = '00:59:59';
$totaltime = date('H:i:s', strtotime($mytime));
$seconds = strtotime("1970-01-01 $totaltime UTC");
$per_seconds = ($mypercentage / 100) * $seconds;
$time_from_percentage = gmdate("H:i:s", $per_seconds);
echo $time_from_percentage;

MySQL & PHP : Time() to Decimal Hour

I have in my MySQL database two Time() saves: start and end.
I would like to have a decimal result of the interval between my two times in my PHP code.
for exemple, if :
start = 15:00:00
end = 16:00:00
result = 1
and if
start = 15:30:00
end = 16:00:00
result = 0,5
Is it possible to get this result using MySQL? If it isn't possible, how could I convert a time format to decimal interval please?
Thanks a lot for reading my issue.
Very straightforward solution would be to take this two values, convert them to time and then make it to hours.
$start = "15:00:00";
$end = "16:00:00";
$result = (strtotime($end) - strtotime($start))/3600;
That gives you $result = 1
For values 15:30:00 and 16:00:00 $result will be 0.5.
Okay,
So I think it is easy. Just follow these steps:
You need to separate those numbers. Make 3 variables. For this example we'll use $hours, $minutes, $seconds (you can achieve these by separating the main time using REGEX. I recommend reading about how to do it first)
Now you have these numbers, for example like so:
$start = "15:30:00";
$start_hours = "15"
$start_minutes = "30"; //or just 0
$start_seconds = "00"; //or just 0
$end = "16:00:00";
$end_hours = "15"
$end_minutes = "00"; //or just 0
$end_seconds = "00"; //or just 0
So... this is briefly how you need to separate those numbers.
Now about the counting...
$result_hours = $end_hours - $start_hours //there you get 1
So hours are easy... For the minutes we need to think about time it self. Cause time values are always in 60 and we need "percents" which are in 100. We'll solve this doing:
$result_minutes = $end_minutes + $start_minutes; //you get 30.. which obviously is NOT what we want.. easily fixed by://
$right_minutes = 100 / 60 * $result_minutes; // gives you 50, which is great.
So far, we have 1,50 (If you'll take enough effort you can simply devide 50 by 10.. you'll get 5)
$result_seconds = $end_seconds + $start_seconds;
$right_seconds = 100 / 60 * $result_seconds;
Now we need to realize that we are dealing with seconds, so the number will be percentage of MINUTES not hours, we can fix this using:
$best_seconds = 100 / 60 * (0.$right_seconds) //now we have all right.
$right = $right_minutes + $best_seconds;
$result = $result_hours.",".$right;
.........................
And that should be it. Hope it will help you figure out the best solution, this is just how I thought it might work.
Try. Change. Try. And Done.
Good Luck

finding out difference between two times

I wrote the following code to determine the amount of time that employees spend on a task:
$time1 = $row_TicketRS['OpenTime'];
$time2= $row_TicketRS['CloseTime'];
$t1=strtotime($time1);
$t2=strtotime($time2);
$end=strtotime(143000); //143000 is reference to 14:30
//$Hours =floor((($t2 - $t1)/60)/60);
$Hours = floor((($end- $t1)/60)/60);
echo $Hours.' Hours ';
The above code is not giving me the correct time.
For example, with a start time of 09:19:00 and end time of 11:01:00 it give me duration time of only 1 hour which is wrong. What is the correct way?
Your use of floor is why you are getting only 1 hour for those inputs. Those inputs result in 1.7 hours if you keep the answer as a float. floor automatically rounds down to the lower integer value. Check out http://php.net/manual/en/function.floor.php for more info.
$t1 = strtotime('09:19:00');
$t2 = strtotime('11:01:00');
$hours = ($t2 - $t1)/3600; //$hours = 1.7
If you want a more fine-grained time difference, you can flesh it out...
echo floor($hours) . ':' . ( ($hours-floor($hours)) * 60 ); // Outputs "1:42"
UPDATE:
I just noted your comments on Long Ears' answer. Please check my comments above again, they are correct. Inputting values of '09:11:00' and '09:33:00' results in 0 hours (22 minutes).
If you input those values and got 4 hours, you likely have a decimal error in your math. Using '09:11' to '09:33', the result is .367 hours. If you divided the strtotime results by 360 instead of by 3600, you would get result 3.67 hours (or 4 hours, depending on your rounding method).
strtotime converts your time to an int value representing number of seconds since Unix epoch. Since you convert both values to seconds, and then subtract the values from each other, the resulting value is a quantity of seconds. There are 3600 seconds in 1 hour.
After changing strtotime('14:30:00') everything working fine.. see below
$time1 = '09:19:00';
$time2= '11:01:00';
echo "Time1:".$t1=strtotime($time1);
echo "<br/>Time2:".$t2=strtotime($time2);
echo "<br/>End:".$end=strtotime('14:30:00');
echo "<br/>Floor value:";
var_dump(floor((($end- $t1)/60)/60));
//$Hours =floor((($t2 - $t1)/60)/60);
$Hours = floor((($end- $t1)/60)/60);
echo $Hours.' Hours ';
function getTimeDiff($dtime,$atime)
{
$nextDay=$dtime>$atime?1:0;
$dep=explode(':',$dtime);
$arr=explode(':',$atime);
$diff=abs(mktime($dep[0],$dep[1],0,date('n'),date('j'),date('y'))-mktime($arr[0],$arr[1],0,date('n'),date('j')+$nextDay,date('y')));
//Hour
$hours=floor($diff/(60*60));
//Minute
$mins=floor(($diff-($hours*60*60))/(60));
//Second
$secs=floor(($diff-(($hours*60*60)+($mins*60))));
if(strlen($hours)<2)
{
$hours="0".$hours;
}
if(strlen($mins)<2)
{
$mins="0".$mins;
}
if(strlen($secs)<2)
{
$secs="0".$secs;
}
return $hours.':'.$mins.':'.$secs;
}
echo getTimeDiff("23:30","01:30");
A better way is to use http://php.net/manual/en/datetime.diff.php
$start_t = new DateTime($start_time);
$current_t = new DateTime($current_time);
$difference = $start_t ->diff($current_t );
$return_time = $difference ->format('%H:%I:%S');
for example the start time is 09:19:00 and end time is 11:01:00 but it give me duration time only 1 hour which is wrong
You are calculating the difference in hours. what is the correct result for "start time is 09:19:00 and end time is 11:01:00"
You need strtotime('14:30') rather than strtotime(143000)
Edit: Actually to my surprise, strtotime(143000) does seem to have the desired effect but only for double-digit hours so I still wouldn't rely on it. Anyway it's not the cause of your problem ;)
You can use $hour = ($end - $t1)/(60*60)
In this the time format is (seconds*minutes*days*months*years) => (60*60*2)

Categories