Sum of hours in multiple dates - php

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;

Related

How to subtract minutes in PHP?

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);

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;
?>

Add up hh:mm written as a string together in php

I am trying to get a total time from few times written as a strings in php.
Times as strings:
00.25, 07.35, 01.10, 00.00, 01.00, 00.22
With that I should get 10hrs12mins but I get 11hrs03mins.
function add()
{
$midnight = strtotime('0.00');
$extra = strtotime(hours($extratime));
$taxi = strtotime(hours($taxitime));
$flt = strtotime($flttime);
$res = strtotime(hours($options->restime));
$hold = strtotime(hours($holdtime));
$totalseconds = $extra + $taxi + $flt + $res + $hold;
return date("H.i", $midnight + $totalseconds);
}
$holdtime, $taxitime, $extratime, $options->restime are all written as minutes and then converted to hours using:
function hours($min)
{
$mins = abs($min);
$neg = ($min < 0) ? '-' : '' ;
$hours = $mins / 60;
$onlyhours = floor($hours);
$onlymins = $mins - ($onlyhours*60);
$time = sprintf("%s%d.%02d",$neg,$onlyhours,$onlymins);
return $time;
}
The function hours works fine but function add doesn't as after displaying it I get 11.03 where it should be 10.12.
Thanks in advance,
Maciej.
Do not convert $holdtime, $taxitime, $extratime, $options->restime in hours.
Add these durations in minutes :
$total = $holdtime + $taxitime + $extratime + $options->restime;
Then convert $total in hours.

function for converting time to number of seconds

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");

Get Difference Between Two Times (Unix Epoch)

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);

Categories