How to add multiple date ranges as php

Asked

Viewed 937 times

3

I have a problem with the sum of dates. I have several events that are registered in the bank with initial date and final date, I need to know the time interval between these events and add up these intervals to know the total time that lasted these events. To calculate the time difference of an event I use the method diff class DateTime, but I can’t add up those intervals. Someone can help me?

Follow the code below:

$intervalo1 = date_diff($objDataInicio1, $objDataFim1);
$intervalo2 = date_diff($objDataInicio2, $objDataFim2);
$somaDosIntervalos = $intervalo1+$intervalo2 ?????

I can even sum up the numbers of days, months and years, but that doesn’t work because the sum value is as integer not as date, so if you have 25 days in the first interval and 20 days in the second the result of the calculation will be 45 days, not 1 month and 15 days.

2 answers

1

You can accomplish this using the method diff of the object Datetime:

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R');
echo $interval->format('%a');

// Diferença de dias do primeiro intervalo de datas
$s = $interval->format('%R');
$d1 = $interval->format('%a') * ($s == '-' ? -1 : 1); 

echo PHP_EOL;

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-05');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R');
echo $interval->format('%a');

// Diferença de dias do primeiro intervalo de datas
$s = $interval->format('%R');
$d2 = $interval->format('%a') * ($s == '-' ? -1 : 1);

echo PHP_EOL;

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-25');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R');
echo $interval->format('%a');

// Diferença de dias do primeiro intervalo de datas    
$s = $interval->format('%R');
$d3 = $interval->format('%a') * ($s == '-' ? -1 : 1);

echo PHP_EOL;

echo 'Soma do intervalo: ' . ($d1 + $d2 + $d3) . ' dias';

Exit:

+2
-6
+14
Soma do intervalo: 10 dias

0

$data1 = new DateTime( '2013-12-11' );
$data2 = new DateTime( '1994-04-17' );

$intervalo = $data1->diff( $data2 );

echo "Intervalo é de {$intervalo->y} anos, {$intervalo->m} meses e     {$intervalo->d} dias";
  • Vanderson, this I had done, but I want to add up the diff of several different dates

Browser other questions tagged

You are not signed in. Login or sign up in order to post.