I would like to know how to subtract two variables that represent minutes in PHP
For example I have two minute variables
$minutes1 = 20;
$minutes2 = 45;
$totalMinutes = $minutes1 -$minutes2;
//output should be 35 as $totalMinutes
An example would be
$time1 = "2:20";
$time2 = "3:45";
$finalTime = $time2 - $time1
//final time = 1:25
I am only interested in the minutes and not the hours
I bet that there's some cleaner way, but this seem to do what you're asking for.
$m1 = 20;
$m2 = 45;
$diff = $m1 - $m2;
echo $diff >= 0 ? $diff : $diff + 60;
This returns 35. Demo: https://3v4l.org/WaC8r
EDIT: Based on comments I have a better understanding of what you are asking for and have written this function.
function subtractMinutes($start, $sub) {
$res = $start;
while ($sub > 0) {
if ($sub >= 60) {
$sub -= 60;
continue;
}
if ($res >= $sub) {
$res -= $sub;
break;
}
if ($sub > $res) {
$sub -= $res + 1;
$res = 59;
continue;
}
$sub -= $res;
$res = 0;
}
return $res;
}
var_dump(subtractMinutes(20, 45)); //35
var_dump(subtractMinutes(20, 60)); //20
var_dump(subtractMinutes(20, 120)); //20
var_dump(subtractMinutes(20, 121)); //19
var_dump(subtractMinutes(40, 40)); //0
var_dump(subtractMinutes(59, 58)); //1
Please note that this answer attempts to provide a general solution.
If you only need to subtract a couple of times by all means, just
check with 60.
I would insist on suggesting you should be using decimals for all operations, and only turn into the correct format when outputting the result on a page. I believe it is safer to do calculations this way, instead of relying on you remembering to add/subtract 60 every time.
Examples:
$single_minute = 1.66;
$twenty_minutes = 20*1.66 = 33.2;
$sixty_minutes = 60*1.66 = 99.6;
When outputing:
$out_twenty = round(33.2/1.66);
$out_sixty = round(99.6/1.66);
You can use helper constants:
define("MINUTE", 1.66);
//You want to calculate 34 minutes
$thirtyfour_minutes = MINUTE * 34;
//You want to output 34 minutes
echo round($thirtyfour_minutes);
Related
I have an To make a sum of hours.
foreach ($horaires as $horaire) {
$addition += strtotime($horaire->getPointNbh()->format('H:m:s'));
}
And it s not working. Somebody can help me about how to make operations on DateTimne Type with Symfony 2.
Thanks
Without Solution in side of Symfony or Datetime object, this is my solution:
$heure = 0;
foreach ($horaires as $horaire) {
$heure += $horaire->getPointNbh()->format('H') *3600 + $horaire->getPointNbh()->format('i') *60 + $horaire->getPointNbh()->format('s'); ;
//$heure = $heure * 3600;
}
$hour = floor($heure /3600);
$min = floor($heure%3600/60);
$sec = $heure - (($hour*3600) + ($min*60));
$result = $hour.":".$min.":".$sec;
return $result;
I have some total sums of hours and need to calculate the average. For example, my total hour value is 2452:43:44 (H:m:s) and the total count is 15. I would like to get the average time in the same format, that is hours:minutes:seconds. How can we do it in PHP ?
function average_time($total, $count, $rounding = 0) {
$total = explode(":", strval($total));
if (count($total) !== 3) return false;
$sum = $total[0]*60*60 + $total[1]*60 + $total[2];
$average = $sum/(float)$count;
$hours = floor($average/3600);
$minutes = floor(fmod($average,3600)/60);
$seconds = number_format(fmod(fmod($average,3600),60),(int)$rounding);
return $hours.":".$minutes.":".$seconds;
}
echo average_time("2452:43:44", 15); // prints "163:30:55"
echo average_time("2452:43:44", 15, 2); // prints "163:30:54.93"
Close to Antony's solution, but with array of hours given:
$time = array (
'2452:43:44',
'452:43:44',
'242:43:44',
'252:43:44',
'2:43:44'
);
$seconds = 0;
foreach($time as $hours) {
$exp = explode(':', strval($hours));
$seconds += $exp[0]*60*60 + $exp[1]*60 + $exp[2];
}
$average = $seconds/sizeof( $time );
echo floor($average/3600).':'.floor(($average%3600)/60).':'.($average%3600)%60;
$totalhourandmunite+=str_replace(":",'',$date);
strtoheur(round($totalhourandmunite/$nbdate,0));
function strtoheur($temp)
{
if(strlen($temp)==1) return $temp;
if(strlen($temp)==2)
$temp=$temp."00";
if(strlen($temp)==3)
$temp="0".$temp;
$temp=str_split($temp);
$heure=$temp["0"].$temp["1"];
$min=$temp["2"].$temp["3"];
if($min/60>1)
{
$min=$min%60;
$heure++;
}
if($min<10 && strlen($min)==1)
$min="0".$min;
if($heure>23)
{
$heure=$heure%24;
}
$temp=$heure.":".$min;
return $temp;
}
The best way would be to change the total hour value in seconds.
Divide it by total count value. What you will get is average in seconds.
Convert average back in H:m:s format.
On our site, we have a lot of swimming times that we would like to convert to seconds. i.e. 1:23:33.03 or 58:22.43. Is there a PHP function that can do this? A MySQL function?
http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_time-to-sec
mysql> SELECT TIME_TO_SEC('22:23:00');
-> 80580
mysql> SELECT TIME_TO_SEC('00:39:38');
-> 2378
function time2seconds($time='00:00:00')
{
list($hours, $mins, $secs) = explode(':', $time);
return ($hours * 3600 ) + ($mins * 60 ) + $secs;
}
From here.
MySQL also has TIME_TO_SEC()
so if mysql without fractions not appropriate solution - here is another mine
$time = '1:23:33.03';
$parts = explode(':', $time);
$seconds = 0;
foreach ($parts as $i => $val) {
$seconds += $val * pow(60, 2 - $i);
}
echo $seconds;
Use the following program for converting time to seconds in php.
<?php
function time_to_sec($time) {
$hours = substr($time, 0, -6);
$minutes = substr($time, -5, 2);
$seconds = substr($time, -2);
return $hours * 3600 + $minutes * 60 + $seconds;
}
$result=time_to_sec('12:25:59');
echo $result;
?>
$current_time_in_seconds="01:21:44.24";
list($hours, $minutes, $seconds) = explode(":", $current_time_in_seconds);
$current_time_in_seconds=$hours*3600+$minutes*60+$seconds;
will get from
01:21:44.24
to
4904.24
Strtotime is what you need. You get a Unix timestamp which in this case would be the number of seconds.
I am a little confused but I think that you mean. 1 hour, 23 minuts and 23.03 seconds.
this is not difficult to do. I made this PHP function that does that. My php server doesn't want to start up, so I couldn't test it, but I think it should work.
function ConvertTimeToSeconds($T)
{
$exp = explode(":",$T);
$c = count($exp);
$r = 0;
if ($c == 2)
{
$r = (((int)$exp[0]) * 60) + ((int)$exp[1]);
}else{
$r = (((int)$exp[0]) * 3600) + (((int)$exp[1]) * 60) + ((int)$exp[2]);
}
return $r;
}
ConvertTimeToSeconds("1:23:33.03");
You know when it's late in the night and your brain is fried? I'm having one of those nights right now, and my function so far is not working as it should, so please take a look at it:
(I should note that I'm using the PHP 5.2.9, and the function / method DateTime:Diff() is not available until PHP 5.3.0.
<?php
function time_diff($ts1, $ts2) {
# Find The Bigger Number
if ($ts1 == $ts2) {
return '0 Seconds';
} else if ($ts1 > $ts2) {
$large = $ts1;
$small = $ts2;
} else {
$small = $ts1;
$large = $ts2;
}
# Get the Diffrence
$diff = $large - $small;
# Setup The Scope of Time
$s = 1; $ss = 0;
$m = $s * 60; $ms = 0;
$h = $m * 60; $hs = 0;
$d = $h * 24; $ds = 0;
$n = $d * 31; $ns = 0;
$y = $n * 365; $ys = 0;
# Find the Scope
while (($diff - $y) > 0) { $ys++; $diff -= $y; }
while (($diff - $n) > 0) { $ms++; $diff -= $n; }
while (($diff - $d) > 0) { $ds++; $diff -= $d; }
while (($diff - $h) > 0) { $hs++; $diff -= $h; }
while (($diff - $m) > 0) { $ms++; $diff -= $m; }
while (($diff - $s) > 0) { $ss++; $diff -= $s; }
# Print the Results
return "$ys Years, $ns Months, $ds Days, $hs Hours, $ms Minutes & $ss Seconds.";
}
// Test the Function:
ediff(strtotime('December 16, 1988'), time());
# Output Should be:
# 20 Years, 11 Months, 8 Days, X Hours, Y Minutes & Z Seconds.
?>
This isn't an answer to your question, but I just wanted to point out...
while (($diff - $y) > 0) { $ys++; $diff -= $y; }
is a very inefficient way of writing
$ys = $diff / $y;
$diff = $diff % $y;
Also, this
else if ($ts1 > $ts2) {
$large = $ts1;
$small = $ts2;
} else {
$small = $ts1;
$large = $ts2;
}
# Get the Diffrence
$diff = $large - $small;
can easily be rewritten as
$diff = abs($ts1 - $ts2);
I have a feeling that the problem in your code would be more apparent if it was less verbose. :)
how about simplifying the first part with a simple
$diff = abs($ts2 - $ts1);
Then, when you do this:
$n = $d * 31; $ns = 0;
$y = $n * 365; $ys = 0;
you are actually saying that a year is composed of 365 31 day long months. which is actually about 36 year long years. Probably not what you want.
Finally, we are all grown ups here. Please use grown up variable names i.e. $YEAR_IN_SECONDS instead of $ys. As you can clearly see, you may write code once, but 20 other schmucks are going to have to read it a lot of times.
In the case of needed all months during the given times-stamp then we have use of the following coding in php :
function MonthsBetweenTimeStamp($t1, $t2) {
$monthsYear = array();
$lastYearMonth = strtotime(gmdate('F-Y', $t2));
$startYearMonth = strtotime(gmdate('F-Y', $t1));
while ($startYearMonth < $lastYearMonth) {
$monthsYear[] = gmdate("F-Y", $startYearMonth);
//Increment of one month directly
$startYearMonth = strtotime(gmdate("F-Y", $startYearMonth) . ' + 1 month');
}
if (empty($monthsYear)) {
$monthsYear = array($startYearMonth));
}
return $monthsYear;
How about this:
function time_diff($t1, $t2)
{
$totalSeconds = abs($t1-$t2);
$date = getdate($totalSeconds);
$firstYear = getdate(0);
$years = $date['year']-$firstYear['year'];
$months = $date['mon'];
$days = $date['mday'];
$hours = $date['hour'];
$minutes = $date['minutes'];
$seconds = $date['seconds'];
return "$years Years, $months Months, $days Days, $hours Hours, $minutes Minutes & $seconds Seconds.";
}
This uses the difference of the given times as a date. Then you can let the "getdate" do all the work for you. The only challenge is the number years - which is simply the getdate year (of the difference) minus the Unix epoch year (1970).
If you don't like using an actual month, you could also divide the "year" day by the number of days in 12 equal months
$months = $date['yday'] / (365/12);
Similarly days could be figured out the remaining days with modulus
$days = $date['yday'] % (365/12);
I have a list of video segment durations I need to add up to get the total duration.
The series is like this:
0:33
4:30
6:03
2:10
...etc
I need to add up the minutes and seconds to get a total video duration.
Here's the modified function of my accepted answer:
function getTotalDuration ($durations) {
$total = 0;
foreach ($durations as $duration) {
$duration = explode(':',$duration);
$total += $duration[0] * 60;
$total += $duration[1];
}
$mins = floor($total / 60);
$secs = str_pad ( $total % 60, '2', '0', STR_PAD_LEFT);
return $mins.':'.$secs;
}
Just made sure the output looks correct.
Give this code a shot:
function getTotalDuration ($durations) {
$total = 0;
foreach ($durations as $duration) {
$duration = explode(':',$duration);
$total += $duration[0] * 60;
$total += $duration[1];
}
$mins = $total / 60;
$secs = $total % 60;
return $mins.':'.$secs;
}
This stores the result in $seconds:
$seconds = 0;
foreach ($times as $time):
list($m,$s) = explode(':',$time);
$seconds += $s + 60*$m;
endforeach;
Convert all times to seconds, add them as integers, convert the sum back to minutes and seconds?