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 ?
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.
You can convert them to timestamps and go from there: $hourdiff = round((strtotime($time1) - strtotime($time2))/3600, 1);
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.
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 );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With