How to sum several date ranges as php [duplicate]

3

I have a problem with the sum of dates. I have several events that are registered in the bank with start date and end date, I need to know the time interval between these events and add these intervals to know the total time that these events lasted. To calculate the time difference of an event I use the diff method of class DateTime , but I can not add these intervals. Can anyone help me?

The following is the code below:

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

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

    
asked by anonymous 22.06.2015 / 22:55

2 answers

1

You can accomplish this using the diff of DateTime object :

$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';

Output:

+2
-6
+14
Soma do intervalo: 10 dias
    
22.06.2015 / 23:32
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";
    
22.06.2015 / 23:00