PHP time add HH:MM:SS - php

I am trying to add total worked hrs for the employees for the 7 days week period below code is not working for me, not sure what am i doing wrong as I am not a PHP expert, idea please?
<?php
$time1 = $row_Roster['sunday_start'];
$time2 = $row_Roster['sunday_end'];
list($hours, $minutes, $seconds) = explode(':', $time1);
$startTimestamp = mktime($hours, $minutes, $seconds);
list($hours, $minutes, $seconds) = explode(':', $time2);
$endTimestamp = mktime($hours, $minutes, $seconds);
$add = $endTimestamp - $startTimestamp;
if($seconds < 0) {
$seconds+=60*60*24;
}
$seconds = $add % 60;
$minutes = ($add / 60) % 60;
$hours = floor($add / (60 * 60));
$sunday = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
echo $sunday;
if ($sunday >8)
echo ('</br><span class="smallred">Long Shift</span>');
?>
does it make sense
list($hours, $minutes, $seconds) = explode(':', $time1);
$Timestamp1 = mktime($hours, $minutes, $seconds);
list($hours, $minutes, $seconds) = explode(':', $time2);
$Timestamp2 = mktime($hours, $minutes, $seconds);
list($hours, $minutes, $seconds) = explode(':', $time3);
$Timestamp3 = mktime($hours, $minutes, $seconds);
list($hours, $minutes, $seconds) = explode(':', $time4);
$Timestamp4 = mktime($hours, $minutes, $seconds);
$add = $Timestamp1 + $Timestamp2 + $Timestamp3 + $Timestamp4;
if($seconds < 0) {
$seconds+=60*60*24;
}
$seconds = $add % 60;
$minutes = ($add / 60) % 60;
$hours = floor($add / (60 * 60));
$total = sprintf('%02d:%02d:%02d', $hours, $minutes, $seconds);
echo $total;
?>

You make this way to complicated.
First just put all your formatted days into an array ($formattedWorkTimeWeekdays).
Then go through each day with array_map() and calculate the total amount of seconds per day and save it in $secondsWorkTimeWeekdays.
After this you can sum all seconds per day together with array_sum() and you get the total amount of work for this week in seconds in the variable $totalSecondsWorkTimeWeek.
And at the end simply calculate the hours, minutes and seconds out of it.
<?php
$formattedWorkTimeWeekdays = [
$monday,
$tuesday,
$wednesday,
$thursday,
$friday,
$saturday,
$sunday,
];
$secondsWorkTimeWeekdays = array_map(function($formattedWorkTimeDay){
list($hours, $minutes, $seconds) = explode(":", $formattedWorkTimeDay);
return ($hours * 3600) + ($minutes * 60) + $seconds;
}, $formattedWorkTimeWeekdays);
$totalSecondsWorkTimeWeek = array_sum($secondsWorkTimeWeekdays);
$hoursWorkTimeWeek = $totalSecondsWorkTimeWeek / 3600;
$minutesWorkTimeWeek = ($totalSecondsWorkTimeWeek % 3600) / 60;
$secondsWorkTimeWeek = ($totalSecondsWorkTimeWeek % 3600 % 60);
echo $total = sprintf('%02d:%02d:%02d', $hoursWorkTimeWeek, $minutesWorkTimeWeek, $secondsWorkTimeWeek);
?>
EDIT:
After your edit your have 2 completely different codes, which aren't related to each other at all. For your first revision I gave the answer above.
Now in your edited code you just seem to have 2 dates. You can just create two DateTime objects and get the difference from them, e.g.
$workTimeStart = new DateTime($row_Roster['sunday_start']);
$workTimeEnd = new DateTime($row_Roster['sunday_end']);
$workTimeDifference = $workTimeStart->diff($workTimeEnd);
echo $workTimeDifference->format("%h hours %i minutes %s seconds");

Instead of calculations and calling sprintf, you can use gmdate function:
//the same code summing the weekdays seconds
$add = $Timestamp1 + $Timestamp2 + $Timestamp3 + $Timestamp4;
print gmdate("H:i:s", $add);

Related

convert negative seconds into hh:mm:ss format

wanne have a function that convert positive and negative seconds in Timeformat h:i:s
So i have value like
$seconds= -41880;
Try with first function
function secToHR($seconds)
{
$hours = floor($seconds / 3600);
$mins = floor($seconds / 60 % 60);
$secs = floor($seconds % 60);
$time = sprintf('%02d:%02d:%02d', $hours, $mins, $secs);
return $time;
}
result is
$time = -12:-38:00
When i use a positive value for $seconds
$seconds = 100380
then result is like
$time = 27:53:00
what is correct
Then second function
function secToHR2($seconds)
{
$time = gmdate("h:i:s", abs($seconds));
if ($seconds < 0) {
$time = '-' . $time;
}
return $time;
}
for
$seconds= -41880
result
$time = -11:38:00
wich is correct
but for
$seconds = 100380
result is now
$time : 03:53:00
which is now wrong
Does someone have the clue which functions i need and modified so that it is working correct for positive and negative values
gmdate() (and the other date-time functions as well) represents the number of seconds passed as argument as a date, not as a number of hours, minutes and seconds. It never returns a value greater than 23 for h and so on.
Combine the logic of the two functions: use the code of secToHR() to format the absolute value of its argument and the logic of secToHR2() to handle the sign.
function secToHR($seconds)
{
// Separate the sign and the absolute value of $seconds
$sign = '';
if ($seconds < 0) {
$sign = '-';
$seconds = -$seconds;
}
// Compute the components
$secs = $seconds % 60;
$minutes = ($seconds - $secs) / 60;
$mins = $minutes % 60;
$hours = ($minutes - $mins) / 60;
// P
return sprintf('%s%02d:%02d:%02d', $sign, $hours, $mins, $secs);
}
The easiest thing to do is to
extract any negative sign
call your function that's only defined for positive values (secToHR)
reinsert the negative sign if appropriate

Why hour showing wrong after strtotime() conversion

i use this url for time to minutes conversion but extra hour are shown where there is no hour in time.
my code is
<?php
$seconds=strtotime('00:11:10').'<br/>';
echo gmdate('H:i:s',$seconds).'<br/>';
$H = floor(($seconds / 3600));
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);
?>
the output showing 389496:11:10 //it should 00:11:10
what the problem is...??
I really getting pain on this any help would be appreciated .
This is the snippet I use for HH:MM:SS to minutes conversion.
<?php
$str_time = "00:11:10";
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = $hours * 3600 + $minutes * 60 + $seconds;
$minutes = $time_seconds / 60;
echo $minutes;
The output, as you expect, is 11.166666666667.
If the time is 1 hour, 20 minutes and 10 seconds, the output is then: 80.166666666667
I'd venture to say because you append <br> to the $seconds, and then use it with math functions like $seconds/3600 ... etc .. remove the <br> and add it later, or remove the <br> altogether
$seconds=strtotime('00:11:10');
echo gmdate('H:i:s',$seconds).'<br/>';
$H = floor(($seconds / 3600));
$i = ($seconds / 60) % 60;
$s = $seconds % 60;
echo sprintf("%02d:%02d:%02d", $H, $i, $s);

Wrong time calculated having more than 30min

Im having a a bit strange problem, Im having this code and on output it adds always one hour more if the second time has 30 or more minutes.
$time1 = '12:00';
$time2 = '13:30';
list($hours, $minutes) = explode(':', $time1);
$startTimestamp = mktime($hours, $minutes);
list($hours, $minutes) = explode(':', $time2);
$endTimestamp = mktime($hours, $minutes);
$seconds = $endTimestamp - $startTimestamp;
$minutes = ($seconds / 60) % 60;
$hours = round($seconds / (60 * 60));
Whats happening here?
Remember the math. Rounding up everything in interval [0.5;1) equals to 1.
round(0.5) = 1
That's why you've +1 hour in case of minutes in [30;60].
Instead of using round use intval as $seconds / (60 * 60) expression always returns a float and we need only the integer part of that result

Subtract Time String in PHP

Say I have the following as a string:
$timeLeft = 00:02:30
I want to be able to subtract 1 second, turning it into 00:02:29.
I have tried
$timeLeft - 1;
But it does nothing.
How can I make it so I can subtract seconds from a string?
You need to convert it to a time, subtract 1 second and reformat, e.g.:
$timeLeft = '00:02:30';
$time = DateTime::createFromFormat('H:i:s', $timeLeft);
$time->sub(new DateInterval('PT1S'));
$timeLeft = $time->format('H:i:s');
Below is dirty code that performs the transformation "manually" by converting the time into seconds in case PHP 5.3+ is not available. It'll certainly misbehave it the number of seconds subtracted is greater than the total.
$timeLeft = '00:02:30';
list($hours, $minutes, $seconds) = explode(':', $timeLeft);
$seconds += $hours*3600 + $minutes*60;
unset($hours, $minutes);
$seconds -= 1; //subtraction
$hours = floor($seconds/3600);
$seconds %= 3600;
$minutes = floor($seconds/60);
$seconds %= 60;
$timeLeft = sprintf("%'02u:%'02u:%'02u", $hours, $minutes, $seconds);
Using strtotime is a good practical solution, but you have to watch out for DST changes:
$tz = date_default_timezone_get(); // save old timezone
date_default_timezone_set('UTC'); // switch to UTC
echo date('H:i:s', strtotime($timeleft) - 1); // perform calculation
date_default_timezone_set($tz); // restore old setting

Does not get the time difference correct in PHP

$time1 = "01:00";
$time2 = "04:55";
list($hours1, $minutes1) = explode(':', $time1);
$startTimestamp = mktime($hours1, $minutes1);
list($hours2, $minutes2) = explode(':', $time2);
$endTimestamp = mktime($hours2, $minutes2);
$seconds = $endTimestamp - $startTimestamp;
$minutes = ($seconds / 60) % 60;
$hours = round($seconds / (60 * 60));
echo $hours.':'.$minutes;
exit;
Outputs 4:55, should be 3:55 ?
Whats wrong here? If it is 01:00 and 02:00, it works fine, but not with the above?
Use floor instead of round...
Or just cast to integer.
$hours = (int) ($seconds / (60 * 60));
Too many calculations when PHP can do it for you with also reducing possibility of error
$time1 = Datetime::createFromFormat("h:i", "01:00");
$time2 = Datetime::createFromFormat("h:i", "04:55");
$diff = $time1->diff($time2);
var_dump($diff->format("%h %i"));
Output
string '3:55' (length=4)
You can also save yourself some time by using strtotime:
$time1 = strtotime("01:00");
$time2 = strtotime("04:55");
$seconds = $time2-$time1;
$minutes = ($seconds / 60) % 60;
$hours = floor($seconds / (60 * 60));
echo $hours.':'.$minutes;
As mentioned, using floor will produce the result you need:
Result
3:55

Categories