Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Average dateInterval php

Hello i need to calculate an average time between some DateInterval.

Actually i've some Dateinterval like this :

for ($i = 0 ; $i < count($startDate) ; $i++)
    {
          $diffTable[] = date_diff($finishDate[$i], $startDate[$i]);
          echo $diffTable[$i]->format("%Y-%M-%d %H:%i:%s");
    }

Here is the output :

00-00-0 00:13:17
00-00-0 00:7:47
00-00-0 00:7:14
00-00-0 00:10:39

I need to calculate the average time between this intervals. Here it's only minute and second, but it could be Month or year.

I can't find a good way to calculate it easily. i can simply add every dateInterval with a conversion like this :

sec + 60xmin + 3600xHour ...

And them play with Modulo (%).

But i hope there is another way ?

like image 844
Damien Locque Avatar asked Jul 26 '12 09:07

Damien Locque


People also ask

What is DateInterval in PHP?

Represents a date interval. A date interval stores either a fixed amount of time (in years, months, days, hours etc) or a relative time string in the format that DateTimeImmutable's and DateTime's constructors support.

How can I calculate hours between two dates in PHP?

You can convert them to timestamps and go from there: $hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);

How can I calculate total hours in PHP?

There are two ways to calculate the total time from the array. Using strtotime() function: The strtotime() function is used to convert string into the time format. This functions returns the time in h:m:s format. Example 1: This example reads the values from the array and converts it into the time format.

How do I use DateInterval?

Creating a DateInterval Object Let's define a predictable duration, create a DateInterval object, and output the result to the screen. We'll start with “1 year, 2 months, 3 days, 4 hours, 5 minutes, 6 seconds”. $Duration = new DateInterval( "P1Y2M3DT4H5M6S" ); print_r( $Duration );


1 Answers

Ok untif i found sth better i just write this :

function dateIntervalToSecond($interval)
    {
        return $interval->y     * 31556926 
                + $interval->m  * 2629743
                + $interval->d  * 6400
                + $interval->h  * 3600
                + $interval->i  * 60
                + $interval->s;
    }

It's not perfect, But better than nothing.

like image 141
Damien Locque Avatar answered Sep 19 '22 22:09

Damien Locque