How do suptract 33 hours - 30 min in PHP [duplicate] - php

This question already has answers here:
Calculate difference (in hours) between two times in PHP
(2 answers)
Closed 4 months ago.
My Code is :
$hm = strtotime('33:00:00')-strtotime('00:30:00');
$hms = gmdate("H:i:s", $hm);
i need the output is 32:30:00

Use this code to get subtracted values.
$time1 = '33:00:00';
$time2 = '00:00:00';
echo 'Subtract = '.subtractTwoTimes($time1, $time2);
function subtractTwoTimes($time1, $time2){
$time1_parts = explode(':', $time1);
$time1_hours = $time1_parts[0];
$time1_mins = $time1_parts[1];
$time1_secs = $time1_parts[2];
$time2_parts = explode(':', $time2);
$time2_hours = $time2_parts[0];
$time2_mins = $time2_parts[1];
$time2_secs = $time2_parts[2];
$total_hours = $time1_hours - $time2_hours;
$total_mins = $time1_mins - $time2_mins;
$total_secs = $time1_secs - $time2_secs;
if($total_secs < 0){
$total_secs += 60;
$total_mins--;
}
if($total_mins < 0){
$total_mins += 60;
$total_hours --;
}
return $total_hours.':'.$total_mins.':'.$total_secs;
}

To get added or subtracted value from same function.
This is an edited answer. I optimized the code to make it work for you in one function.
$time1 = '33:00:00';
$time2 = '00:30:00';
echo 'Add = '. addOrSubtractTwoTimes($time1, $time2, 'add');
echo '<br>';
echo 'Subtract = '. addOrSubtractTwoTimes($time1, $time2, 'subtract');
function addOrSubtractTwoTimes($time1, $time2, $operation){
$time1_parts = explode(':', $time1);
$time1_hours = $time1_parts[0];
$time1_mins = $time1_parts[1];
$time1_secs = $time1_parts[2];
$time2_parts = explode(':', $time2);
$time2_hours = $time2_parts[0];
$time2_mins = $time2_parts[1];
$time2_secs = $time2_parts[2];
switch ($operation){
case 'add':
$total_hours = $time1_hours + $time2_hours;
$total_mins = $time1_mins + $time2_mins;
$total_secs = $time1_secs + $time2_secs;
if($total_secs > 59){
$extra_mins = floor($total_secs/60);
$total_secs = $total_secs%60;
$total_mins += $extra_mins;
}
if($total_mins > 59){
$extra_hours = floor($total_mins/60);
$total_mins = $total_mins%60;
$total_hours += $extra_hours;
}
break;
case 'subtract':
$total_hours = $time1_hours - $time2_hours;
$total_mins = $time1_mins - $time2_mins;
$total_secs = $time1_secs - $time2_secs;
if($total_secs < 0){
$total_secs += 60;
$total_mins--;
}
if($total_mins < 0){
$total_mins += 60;
$total_hours --;
}
break;
}
return sprintf('%02d', $total_hours).':'.sprintf('%02d', $total_mins).':'.sprintf('%02d', $total_secs);
}

Related

Calculating shift hours worked and detecting

I have a problem. My English is pretty bad. I need to do an overtime calculation with PHP. There is already a code for this. But when the working time is more than 2 days, the calculation is wrong.
Working Start: 2018-09-09 13:43
Working End: 2018-09-11 07:13
Result: 07:18 | 04:00 | 04:00 | 02:00 | 17:18
I can't figure out the problem, please help.
I'd like to give you more details, but I'm pretty bad. I hope you understand me.
Thanks.
<?php
function intersection($s1, $e1, $s2, $e2,$day) {
return subintersection($s1,$e1,$s2,$e2)+subintersection($s1,$e1,$s2+$day,$e2+$day);
}
function subintersection($s1, $e1, $s2, $e2) {
if ($e1 < $s2)
return 0;
if ($s1 > $e2)
return 0;
if ($s1 < $s2)
$s1 = $s2;
if ($e1 > $e2)
$e1 = $e2;
return $e1 - $s1;
}
function minuteToHours($time, $format = '%02d:%02d') {
if ($time < 1) {
return;
}
$hours = floor($time / 60);
$minutes = ($time % 60);
return sprintf($format, $hours, $minutes);
}
function calculateWork($strstart, $strend, $arg = NULL){
$day= 3600*24;
$strS = strtotime($strstart);
$strE = strtotime($strend);
$date_start = date('Y-m-d', $strS);
$date_end = date('Y-m-d', $strE);
$hour_start = date('H:i', $strS);
$hour_end = date('H:i', $strE);
$start = strtotime($hour_start);
$end = strtotime($hour_end);
if($date_start != $date_end){
$end = $end + 3600*24;
}
$tip1_start = strtotime("06:00");
$tip1_end = strtotime("20:00");
$tip2_start = strtotime("20:00");
$tip2_end = strtotime("00:00") + 3600*24;
$tip3_start = strtotime("00:00");
$tip3_end = strtotime("04:00");
$tip4_start = strtotime("04:00");
$tip4_end = strtotime("06:00");
$tip1 = intersection( $start, $end, $tip1_start, $tip1_end, $day) / 60;
$tip2 = intersection( $start, $end, $tip2_start, $tip2_end, $day) / 60;
$tip3 = intersection( $start, $end, $tip3_start, $tip3_end, $day) / 60;
$tip4 = intersection( $start, $end, $tip4_start, $tip4_end, $day) / 60;
if(null !== minuteToHours($tip1, '%02d:%02d')){
$t1 = minuteToHours($tip1, '%02d:%02d');
}
if(null !== minuteToHours($tip2, '%02d:%02d')){
$t2 = minuteToHours($tip2, '%02d:%02d');
}
if(null !== minuteToHours($tip3, '%02d:%02d')){
$t3 = minuteToHours($tip3, '%02d:%02d');
}
if(null !== minuteToHours($tip4, '%02d:%02d')){
$t4 = minuteToHours($tip4, '%02d:%02d');
}
$topla = $tip1 + $tip2 + $tip3 + $tip4;
$total = minuteToHours($topla, '%02d:%02d');
return "{$t1}|{$t2}|{$t3}|{$t4}|{$total}";
}
echo calculateWork("2018-09-09 13:43", "2018-09-11 07:01");
//07:18|04:00|04:00|02:00|17:18

Sum(ADD) more than two time values in php

$time = array("18:10:00", "23:10:12", "10:05:00");
How to get the total time from this array. I need output like 51:25:12, Please help me
Try this short code:
It fill up your all case. Like as case:$a=array("18:30:00", "23:30:12", "10:05:00");.
function sum_time($array) {
$i = 0;
foreach ($array as $time) {
sscanf($time, '%d:%d:%d', $hour, $min,$sec);
$i += ($hour * 60 + $min)*60+$sec;
}
if ($h = floor($i / 3600)) {
$i %= 3600;
if ($m = floor($i / 60)) {
$i %= 60;
}
}
return sprintf('%02d:%02d:%02d', $h, $m,$i);
}
$a=array("18:30:00", "23:30:12", "10:05:00");
echo sum_time($a);
<?php
$time = array("18:10:00", "23:10:12", "10:05:00");
$hours=0;
$min=0;
$sec=0;
foreach($time as $time_array)
{
$time_exp=explode(':',$time_array);
$hours=$hours+$time_exp[0];
$min=$min+$time_exp[1];
$sec=$sec+$time_exp[2];
}
$time_output='';
$time_output=$hours.':'.$min.':'.$sec;
echo $time_output;
?>
// sample data
$time = array("18:50:00", "23:10:12", "10:05:00");
//variable initialization
$seconds = $mins = $hours = array();
//loop through all sample data items
foreach($time as $tk => $tv) {
//explode each item with seperator
$tv_parts = explode(":", $tv);
$seconds[] = $tv_parts['2'];
$mins[] = $tv_parts['1'];
$hours[] = $tv_parts['0'];
}
//add up all items respectively
$ts = array_sum($seconds);
$tm = array_sum($mins);
$th = array_sum($hours);
//adjust seconds if they are more than 59
if($ts > 59) {
$ts = $ts % 60;
$tm = $tm + floor($ts / 60);
}
//adjust minutes if they are more than 59
if($tm > 59) {
$tm = $tm % 60;
$th = $th + floor($tm / 60);
}
//padding for adjusting it to two digits when sum is below 10
$th = str_pad($th, 2, "0", STR_PAD_LEFT);
$tm = str_pad($tm, 2, "0", STR_PAD_LEFT);
$ts = str_pad($ts, 2, "0", STR_PAD_LEFT);
//final output
echo "$th:$tm:$ts";
You can refer more details about array_sum, floor and str_pad on official documentation site for PHP.
Easiest way to do this is as follows:
$time = array("18:10:00", "23:10:12", "10:05:00");
$sum="00:00:00";
$sum_new = explode(':',$sum);
foreach ($time as $t)
{
$time_new = explode(':',$t);
$sum_new[0]=$sum_new[0]+$time_new[0];
$sum_new[1]=$sum_new[1]+$time_new[1];
$sum_new[2]=$sum_new[2]+$time_new[2];
}
$sum = implode(':',$sum_new);
echo $sum;
First explode current date string via : and than just sum up parts. Don't forget to fix overflow of time parts:
function sum($times) {
$total = array(
'h' => 0,
'm' => 0,
's' => 0,
);
foreach ($times as $t) {
$timeArray = explode(":", $t);
$total['h'] += $timeArray[0];
$total['m'] += $timeArray[1];
$total['s'] += $timeArray[2];
}
if ($total['s'] >= 60) {
$total['m'] += $total['s'] % 60;
$intpart = floor($total['s']);
$total['s'] = $total['s'] - $intpart;
}
if ($total['m'] >= 60) {
$total['h'] += $total['m'] % 60;
$intpart = floor($total['m']);
$total['m'] = $total['m'] - $intpart;
}
return $total;
}
$totals = sum(array("18:10:00", "23:10:12", "10:05:00"));
echo implode(':', $totals);
Try this:
<?php
$time = array("18:10:00", "23:10:12", "10:05:00");
$seconds = 0;
foreach($time as $t)
{
$timeArr = array_reverse(explode(":", $t));
foreach ($timeArr as $key => $value)
{
if ($key > 2) break;
$seconds += pow(60, $key) * $value;
}
}
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60);
$secs = floor($seconds % 60);
echo $hours.':'.$mins.':'.$secs;

PHP Convert from strtotime into time

I need to add multiple time values as in Hours:mins, so I use
strtotime($value1) + strtotime($value2)
to add all of them, how do I put them back as hours:mins ?
cant use
date("h:i")
it only works if hours < 24.
I appreciate your help. Thanks
Here is an function that will sum all your time values in format HH:MM:
function sum_time() {
$i = 0;
foreach (func_get_args() as $time) {
sscanf($time, '%d:%d', $hour, $min);
$i += $hour * 60 + $min;
}
if ($h = floor($i / 60)) {
$i %= 60;
}
return sprintf('%02d:%02d', $h, $i);
}
// use example
echo sum_time('01:05', '00:02', '05:59'); # 07:06
demo
Try this :
function time_convert($s) {
$m = 0; $hr = 0; $td = "now";
if ($s > 59) {
$m = (int)($s/60);
$s = $s-($m*60); // sec left over
$td = "$m min";
}
if ($m > 59) {
$hr = (int)($m / 60);
$m = $m - ($hr*60); // min left over
$td = "$hr hr";
if ($hr > 1) {
$td .= "s";
}
if ($m > 0) {
$td .= ", $m min";
}
}
return $td;
}
And use it:
$time = (int) strtotime($v1) + strtotime($v2);
echo time_convert($time);
May it helps
The function strtotime() returns the time in seconds since January 1 1970 00:00:00 UTC. So adding the return value of this function might not do what you would expect.
Instead of using the date functions we can manipulate the string and perform some basic arithmetic operations:
<?php
$value1 = "12:44";
$value2 = "13:47";
$arr1 = explode(':', $value1);
$arr2 = explode(':', $value2);
$totalMinutes = (int)$arr1[0] * 60 + (int)$arr1[1] + (int)$arr2[0] * 60 + (int)$arr2[1];
$hours = (int) ($totalMinutes / 60);
$minutes = $totalMinutes % 60; // Modulus: remainder when dividing with 60
echo $hours . ':' . $minutes;
?>
Another way with DateTime
$dt1 = new DateTime($value1);
$dt2 = new DateTime($value2);
$interval = $dt1->diff($dt2);
echo $interval->format('%a day(s) %h hour(s) %i minute(s)') . '<br />';
echo ($interval->format('%a') * 24 + $interval->format('%h')) . ' hour(s) ';
echo $interval->format('%i minute(s)');

add time result not correct in PHP

I have problem with adding time which is not correct.
Example:
00:00 + 00:35 = 11:13
it should be 00:35 instead of 11:13
This is my code for above:
echo date('H:i',$total).' + '.$telat2.' = ';
if($telat2 == '00:00'){
$total = $total;}
else{
$total = ($total) + strtotime($telat2);}
echo date('H:i',$total).' ';
I hope everybode=y here could help me..
Thanks in advance..
Update 1
I have just got the right code!
This is the code:
$total_unix = strtotime(date('Y-m-d').' '.$total.':00');
$telat2_unix = strtotime(date('Y-m-d').' '.$telat2.':00');
$begin_day_unix = strtotime(date('Y-m-d').' 00:00:00');
$total = date('H:i', ($total_unix + ($telat2_unix - $begin_day_unix)));
I wonder how can this be happen?
Can anybody explain this to me?
Made a working code for original guestion:
<?php
function AddTime($telat1,$telat2)
{
$telat1 = date_parse_from_format("H:i", $telat1);
$telat2 = $timeToAdd;
$telat2 = date_parse_from_format("H:i", $telat2);
$totalHours = $telat1['hour'] + $telat2['hour'];
$totalMinutes = $telat1['minute'] + $telat2['minute'];
if($totalMinutes >= 60)
{
$totalHours += 1;
$totalMinutes -= 60;
}
if($totalHours >= 24)
{
$totalHours -= 24;
}
// Setting the leading zeros
if(strlen($totalMinutes) < 2)
{
$totalMinutes = "0" . $totalMinutes;
}
if(strlen($totalHours) < 2)
{
$totalHours = "0" . $totalHours;
}
$total = $totalHours . ":" . $totalMinutes;
return $total;
}
$timeNow = date('H:i'); // Base time
$timeToAdd = '12:12'; // 12 hours 12 minutes to be added to $timeNow
$total = AddTime($timeNow, $timeToAdd);
echo $total;
?>

how get php total time?

i have created work total time program in PHP - give input time - 1.30, 2.10, 1.40 and get output time - 4.80(8 hrs). but i need output time - 5.20(8.40 hrs).
Notes: 1.30+2.10+1.40=4.80(8 hrs), but i need 5.20(8.40 hrs). please help me...
1.30 + 2.10 + 1.40 is wrong. Should be:
((1 * 60) + 30) + ((2 * 60) + 10) + ((1 * 60) + 40) = 320 (minutes)
320 minutes = 5 hours and 20 minutes.
You need to keep track of minutes and seconds separately:
$minutes = array();
$seconds = array();
foreach ($times as $time) {
$parts = explode('.', $time);
$minutes[] = $time[0];
$seconds[] = $time[1];
}
$total_minutes = array_sum($minutes);
$total_seconds = array_sum($seconds);
while ($total_seconds > 60) {
$total_minutes++;
$total_seconds -= 60;
}
echo $total_minutes . ' minutes and ' . $total_seconds . ' seconds';
Excerpt from PHP site for your pleasure:
function AddTime ($oldTime, $TimeToAdd) {
$pieces = split(':', $oldTime);
$hours=$pieces[0];
$hours=str_replace("00","12",$hours);
$minutes=$pieces[1];
$seconds=$pieces[2];
$oldTime=$hours.":".$minutes.":".$seconds;
$pieces = split(':', $TimeToAdd);
$hours=$pieces[0];
$hours=str_replace("00","12",$hours);
$minutes=$pieces[1];
$seconds=$pieces[2];
$str = $minutes." minute ".$seconds." second" ;
$str = "01/01/2000 ".$oldTime." am + ".$hours." hour ".$minutes." minute ".$seconds." second" ;
if (($timestamp = strtotime($str)) === false) {
return false;
} else {
$sum = date('h:i:s', $timestamp);
$pieces = split(':', $sum);
$hours = $pieces[0];
$hours = str_replace("12", "00", $hours);
$minutes = $pieces[1];
$seconds = $pieces[2];
$sum = $hours.":".$minutes.":".$seconds;
return $sum;
}
}
$firstTime = "00:03:12";
$secondTime = "02:04:34";
$sum=AddTime($firstTime, $secondTime);
if($sum != false) {
echo $firstTime." + ".$secondTime." = ".$sum;
} else {
echo "failed";
}
Output:
00:03:12 + 02:04:34 = 02:07:46
For each number (represented as $t below) you can do this:
// start with $total=0
$hours = floor($t); // 1.10 -> 1 hr
$minutes = ($t - $hours) * 100; // 1.10 -> 10 mins
$total += ($hours * 60) + $minutes;
That gives you the total number of minutes. To get hours/mins separately, do this:
$total_mins = $total % 60; // 130 -> 10 mins
$total_hours = ($total - $total_mins) / 60; // 130 -> 2 hrs

Categories