I have array of items like this:
Array
(
[0] => 0:16:0
[1] => 0:0:8
[2] => 0:5:0
...
[n] => 0:3:1
)
There could be more arrays, they are symbolize
hours, minutes, seconds.
How can I calculate 0 + 1 + 2 + ... + n and to get final number of hours, minutes and seconds?
Try this code out
$arr = array('0:16:0', '25:12:5', '0:0:10', '0:5:0');
// converting all the times to seconds
$t_seconds = 0;
foreach ($arr as $v) {
sscanf($v, "%d:%d:%d", $hours, $minutes, $seconds);
$t_seconds += $hours * 3600 + $minutes * 60 + $seconds;
}
// condition if seconds calculated are negative
$sign = ($t_seconds < 0 ? '-' : '');
$t_seconds = abs($t_seconds);
// converting seconds, taking care of wrong minutes/seconds formats like 02:63:65
$hours = floor($t_seconds / 3600);
$minutes = floor(($t_seconds / 60) % 60);
$seconds = $t_seconds % 60;
// final format
$sum = $sign . sprintf("%02d:%02d:%02d", $hours, $minutes, $seconds);
Result ($sum variable)
25:33:15
I solved by seperating hours, minutes, secounds as array from my foreach element. Then i call array, using array_sum
( thanks Rizier123 for point me on that function )
// receive values and calculate with current hours
$finalHourPause = array_sum($pauseArrayHours) . "\n";
$finalMinutePause = array_sum($pauseArrayMinutes) . "\n";
$finalSecoundsPause = array_sum($pauseArraySecounds) . "\n";
Related
I have an array with time values
print_r($timeVal);
output:
Array (
[2018-12-01] => 23:58:0
[2018-12-02] => 23:58:0
[2018-12-03] => 23:58:0
[2018-12-05] => 2:0:0
)
so i want to calculate all those and get total time:
correct result should be
73:54 and not 3 days 1 hours 54 minutes 0 seconds
post is not duplicate coz i viewed other posts and they show Day hour minute not just hour min
example like this :
$sum = strtotime('00:00:00');
$sum2=0;
foreach ($TimeVal as $v){
$sum1=strtotime($v)-$sum;
$sum2 = $sum2+$sum1;
}
$sum3=$sum+$sum2;
date("H:i:s",$sum3) //this show 1:54:00
Since you do not want to display your time in a 24-hour format, date() won't give you what you are looking for.
I copied your code and modified it slightly, so it does the job with the example you gave:
$sum = strtotime('00:00:00');
$sum1 = 0;
foreach ($TimeVal as $v){
$sum1 += strtotime($v) - $sum;
}
$hours = $sum1 / 3600;
$minutes = ($hours - floor($hours)) * 60;
echo floor($hours) . ':' . round($minutes);
I am quite new to PHP I need help in implementing the total Hours and minutes in PHP.
I have an array of time in PHP in hours, minutes and seconds
(array) Array
(
[0] => 01:10:00
[1] => 01:20:30
[2] => 00:00:10
)
My Expected output should be the total time in Hours, minutes and seconds (ex. 2:30:40)
$hours;
$minutes;
$seconds;
foreach( $thatArray as $v )
{
$subArray = explode(':', $v);
$hours += $subArray[0];
$minutes += $subArray[1];
$seconds += $subArray[2];
}
// output $hours / $minutes / $seconds, correctly formatting, etc
Not going to give you the codez. here's how you can do it:
Get the individual components of the time using explode()
Start by adding the seconds. If the result is greater than 60, increment minutes and so on.
The easiest way would probably be to convert all of them to a seconds representation, sum them, and convert them back. For example:
function timeToSeconds($time) {
$parts = explode(':', $time);
return $parts[0] * 3600 + $parts[1] * 60 + $parts[2];
}
function secondsToTime($seconds) {
$hours = floor($seconds / 3600);
$minutes = floor($seconds / 60) % 60;
$seconds %= 60;
return str_pad($hours, 2, '0', STR_PAD_LEFT) . ':' . str_pad($minutes, 2, '0', STR_PAD_LEFT) . ':' . str_pad($seconds, 2, '0', STR_PAD_LEFT);
}
$times = array('01:10:00', '01:20:30', '00:00:10');
$total = secondsToTime(array_sum(array_map('timeToSeconds', $times)));
Here's a demo.
I have a value in the database defined as mediumint(11). Currently it returns 3600 if I run a query.
This function here should convert that value to: 1 hr. But it doesn't when I run the function. I get no value.
function strTime($s) {
$d = intval($s/86400);
$s -= $d*86400;
$h = intval($s/3600);
$s -= $h*3600;
$m = intval($s/60);
$s -= $m*60;
if ($d) $str = $d . 'd ';
if ($h) $str .= $h . 'h ';
if ($m) $str .= $m . 'm ';
if ($s) $str .= $s . 's';
return $str;
}
Pretty basic, must be something with the value in the db?
Code that calls this (Joomla specific):
$query = "SELECT streaming_limit FROM #__cc_users WHERE user_id=".$user->id;
$db->setQuery($query);
$steaming_limit = $db->loadResult(); //returns 3600
echo strTime($streaming_limit); //returns nothing
A more robust way to do this is PHP's DateTime and DateInterval classes, which exist specifically for this sort of thing.
The code below creates two DateTime objects, adds the specified number of seconds
to one object and then calculates the interval between the two.
At that point you can format the time difference however you'd like using DateInterval::format
function strTimeDiff($seconds)
{
$date1 = new DateTime();
$date2 = new DateTime();
$date2->add(new DateInterval('PT'.$seconds.'S'));
$interval = $date1->diff($date2);
echo $interval->format('%d days, %h hours, %i minutes, %s seconds');
}
$secs_from_db = 3600;
echo strTimeDiff($secs_from_db);
// 0 days, 1 hours, 0 minutes, 0 seconds
You could try using something like this:
"converts number of seconds to an array containing hours, minutes and seconds separately"
From http://codeaid.net/php/convert-seconds-to-hours-minutes-and-seconds-%28php%29
<?php
/**
* Convert number of seconds into hours, minutes and seconds
* and return an array containing those values
*
* #param integer $seconds Number of seconds to parse
* #return array
*/
function secondsToTime($seconds)
{
// extract hours
$hours = floor($seconds / (60 * 60));
// extract minutes
$divisor_for_minutes = $seconds % (60 * 60);
$minutes = floor($divisor_for_minutes / 60);
// extract the remaining seconds
$divisor_for_seconds = $divisor_for_minutes % 60;
$seconds = ceil($divisor_for_seconds);
// return the final array
$obj = array(
"h" => (int) $hours,
"m" => (int) $minutes,
"s" => (int) $seconds,
);
return $obj;
}
I'm attempting to convert 7500 seconds to minutes, and then the minutes to hours. If it comes out to 2 hours and 5 minutes, as in this example, I'd like to display it as "2 hours and 5 minutes". If its 2 hours even, I just want it to display "2 hours".
7500 divided by 60 divided by 60 comes out to 2.083 (3 repeated). Why does the % return 0? How can I determine if its hours exactly, or if there are minutes to display?
die("Test: " . ((7500 / 60) / 60) % 1);
For conversion, you can use:
function secondsToWords($seconds)
{
/*** return value ***/
$ret = "";
/*** get the hours ***/
$hours = intval(intval($seconds) / 3600);
if($hours > 0)
{
$ret .= "$hours hours ";
}
/*** get the minutes ***/
$minutes = bcmod((intval($seconds) / 60),60);
if($hours > 0 || $minutes > 0)
{
$ret .= "$minutes minutes ";
}
/*** get the seconds ***/
$seconds = bcmod(intval($seconds),60);
$ret .= "$seconds seconds";
return $ret;
}
echo secondsToWords(7500);
Because that is the modulus operator, which gives the remainder of the division.
You want to use /, the division operator, that returns a float. See here
I've created a nice function for that a while ago. It also does years and months (and anything you'd like) if you want.
Source + examples: http://hotblocks.nl/tests/time_ago.php
Function:
<?php
function time_ago( $f_seconds, $f_size = 2, $f_factor = 1.6 ) {
$units = array(
86400*365.25 => array(' year', ' years'),
86400*30 => array(' month', ' months'),
86400*7 => array(' week', ' weeks'),
86400 => array(' day', ' days'),
3600 => array(' hour', ' hours'),
60 => array(' minute', ' minutes'),
1 => array(' second', ' seconds'),
);
if ( isset($GLOBALS['g_units']) && is_array($GLOBALS['g_units']) ) {
$units = $GLOBALS['g_units'];
}
$timeAgo = array();
$seconds = (int)$f_seconds;
foreach ( $units AS $range => $unit ) {
if ( 1 == $range || $seconds >= $range * $f_factor ) {
is_array($unit) || $unit = array($unit, $unit);
$last = count($timeAgo) == $f_size-1;
$round = $last ? 'round' : 'floor';
$num = $round($seconds / $range);
$timeAgo[] = $num . $unit[(int)(1 != $num)];
if ( $last ) {
break;
}
$seconds -= $num * $range;
}
}
$separator = isset($GLOBALS['g_separator']) ? $GLOBALS['g_separator'] : ', ';
return implode($separator, $timeAgo);
}
?>
That's the way the mod (%) operator works. Every integer is divisible by 1, so
n % 1 = 0
for all integral n.
What are you trying to do with the % operator?
Whatever it is, you probably want to apply it on an integral value, like the number of seconds. It doesn't work for non-integral values; they are promoted to int values before the operator is applied.
This question already has answers here:
Convert seconds to Hour:Minute:Second
(30 answers)
Closed 9 years ago.
For some reason I convert a time format like: 03:30 to seconds 3*3600 + 30*60, now. I wanna convert it back to its first (same) format up there. How could that be?
My attempt:
3*3600 + 30*60 = 12600
12600 / 60 = 210 / 60 = 3.5, floor(3.5) = 3 = hour
Now, what about the minutes?
Considering the value can be like 19:00 or 02:51.
I think you got the picture.
And by the way, how to convert 2:0 for example to 02:00 using RegEx?
This might be simpler
gmdate("H:i:s", $seconds)
PHP gmdate
$hours = floor($seconds / 3600);
$mins = floor($seconds / 60 % 60);
$secs = floor($seconds % 60);
If you want to get time format:
$timeFormat = sprintf('%02d:%02d:%02d', $hours, $mins, $secs);
If the you know the times will be less than an hour, you could just use the date() or $date->format() functions.
$minsandsecs = date('i:s',$numberofsecs);
This works because the system epoch time begins at midnight (on 1 Jan 1970, but that's not important for you).
If it's an hour or more but less than a day, you could output it in hours:mins:secs format with `
$hoursminsandsecs = date('H:i:s',$numberofsecs);
For more than a day, you'll need to use modulus to calculate the number of days, as this is where the start date of the epoch would become relevant.
Hope that helps.
Maybe the simplest way is:
gmdate('H:i:s', $your_time_in_seconds);
Let $time be the time as number of seconds.
$seconds = $time % 60;
$time = ($time - $seconds) / 60;
$minutes = $time % 60;
$hours = ($time - $minutes) / 60;
Now the hours, minutes and seconds are in $hours, $minutes and $seconds respectively.
Another solution that will give you the days, hours, minutes, and seconds for a passed-in seconds value:
function seconds_to_time($secs)
{
$dt = new DateTime('#' . $secs, new DateTimeZone('UTC'));
return array('days' => $dt->format('z'),
'hours' => $dt->format('G'),
'minutes' => $dt->format('i'),
'seconds' => $dt->format('s'));
}
print_r(seconds_to_time($seconds_value);
Extra logic will be needed for 'days' if the time is expected to be more than one year. Use str_pad() or ltrim() to add/remove leading zeros.
ITroubs answer doesn't deal with the left over seconds when you want to use this code to convert an amount of seconds to a time format like hours : minutes : seconds
Here is what I did to deal with this:
(This also adds a leading zero to one-digit minutes and seconds)
$seconds = 3921; //example
$hours = floor($seconds / 3600);
$mins = floor(($seconds - $hours*3600) / 60);
$s = $seconds - ($hours*3600 + $mins*60);
$mins = ($mins<10?"0".$mins:"".$mins);
$s = ($s<10?"0".$s:"".$s);
$time = ($hours>0?$hours.":":"").$mins.":".$s;
$time will contain "1:05:21" in this example.
If you were to hardcode it you would use modulus to extract the time as others suggested.
If you are returning the seconds from MySQL database, assuming you don't need the data in seconds format in your app, there is a much cleaner way to do it, you can use MySQL's SEC_TO_TIME and it will return time in hh:mm:ss format.
Eg.
SELECT SEC_TO_TIME(my_seconds_field) AS my_timestring;
Sorry this is too late but maybe useful
function mediaTimeDeFormater($seconds)
{
if (!is_numeric($seconds))
throw new Exception("Invalid Parameter Type!");
$ret = "";
$hours = (string )floor($seconds / 3600);
$secs = (string )$seconds % 60;
$mins = (string )floor(($seconds - ($hours * 3600)) / 60);
if (strlen($hours) == 1)
$hours = "0" . $hours;
if (strlen($secs) == 1)
$secs = "0" . $secs;
if (strlen($mins) == 1)
$mins = "0" . $mins;
if ($hours == 0)
$ret = "$mins:$secs";
else
$ret = "$hours:$mins:$secs";
return $ret;
}
echo mediaTimeDeFormater(216.064000);//3:36
something like this?
if(is_numeric($time)){
$value = array(
"years" => 0, "days" => 0, "hours" => 0,
"minutes" => 0, "seconds" => 0,
);
if($time >= 31556926){
$value["years"] = floor($time/31556926);
$time = ($time%31556926);
}
if($time >= 86400){
$value["days"] = floor($time/86400);
$time = ($time%86400);
}
if($time >= 3600){
$value["hours"] = floor($time/3600);
$time = ($time%3600);
}
if($time >= 60){
$value["minutes"] = floor($time/60);
$time = ($time%60);
}
$value["seconds"] = floor($time);
return (array) $value;
} else{
return (bool) FALSE;
}
grabbed from: http://www.ckorp.net/sec2time.php
Use modulo:
$hours = $time_in_seconds / 3600;
$minutes = ($time_in_seconds / 60) % 60;
just one small additional example
requested time in miliseconds
// ms2time( (microtime(true) - ( time() - rand(0,1000000) ) ) );
// return array
function ms2time($ms){
$return = array();
// ms
$return['ms'] = (int) number_format( ($ms - (int) $ms), 2, '', '');
$seconds = (int) $ms;
unset($ms);
if ($seconds%60 > 0){
$return['s'] = $seconds%60;
} else {
$return['s'] = 0;
}
if ( ($minutes = intval($seconds/60))){
$return['m'] = $minutes;
}
if (isset($return['m'])){
$return['h'] = intval($return['m'] / 60);
$return['m'] = $return['m'] % 60;
}
if (isset($return['h'])){
$return['d'] = intval($return['h'] / 24);
$return['h'] = $return['h'] % 24;
}
if (isset($return['d']))
$return['mo'] = intval($return['d'] / 30);
foreach($return as $k=>$v){
if ($v == 0)
unset($return[$k]);
}
return $return;
}
// ms2time2string( (microtime(true) - ( time() - rand(0,1000000) ) ) );
// return array
function ms2time2string($ms){
$array = array(
'ms' => 'ms',
's' => 'seconds',
'm' => 'minutes',
'h' => 'hours',
'd' => 'days',
'mo' => 'month',
);
if ( ( $return = ms2time($ms) ) && count($ms) > 0){
foreach($return as $key=>$data){
$return[$key] = $data .' '.$array[$key];
}
}
return implode(" ", array_reverse($return));
}
Here is another way with leading '0' for all of them.
$secCount = 10000;
$hours = str_pad(floor($secCount / (60*60)), 2, '0', STR_PAD_LEFT);
$minutes = str_pad(floor(($secCount - $hours*60*60)/60), 2, '0', STR_PAD_LEFT);
$seconds = str_pad(floor($secCount - ($hours*60*60 + $minutes*60)), 2, '0', STR_PAD_LEFT);
It is an adaptation from the answer of Flaxious.
If You want nice format like: 0:00:00 use str_pad() as #Gardner.
1 day = 86400000 milliseconds.
DecodeTime(milliseconds/86400000,hr,min,sec,msec)
Ups! I was thinking in delphi, there must be something similar in all languages.