Make an algorithm to calculate the number of days elapsed between two dates

1

I have algorítimo done in C but I decided to do in PHP . algorítimo asks for this:

It will calculate the number of days elapsed between two dates including leap years, knowing that:

a) Each pair of dates is read in a row, the last row contains the negative day number

b) The first date in the line is always the oldest. The year is typed with four digits.

I've reached this point:

<?php
    $dia1 = 12;
    $mes1 = 02;
    $ano1 = 2011;

    $dia2 = 20;
    $mes2 = 02;
    $ano2 = 2013;


    // dias do ano1 ate ano2
    $diasTotalAno = 0;
    for ($i=$ano1; $i<$ano2 ; $i++) { 

        // se for float, nao é bissexto
        if (is_float($i/4)) {
            $diasTotalAno += 365;
        } else {
            $diasTotalAno += 366;
        }
    }
    echo "Dias total entre ".$ano1." e ".$ano2." é: ".$diasTotalAno."<br>";


?>

Can anyone help me solve this problem?

    
asked by anonymous 23.04.2015 / 18:56

2 answers

1

You can use DateTime for this

<?php
$dia1 = "12";
$mes1 = "02";
$ano1 = "2011";

$dia2 = "20";
$mes2 = "02";
$ano2 = "2013";

$data1 = DateTime::createFromFormat("dmY", $dia1 . $mes1 . $ano1);
$data2 = DateTime::createFromFormat("dmY", $dia2 . $mes2 . $ano2);

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

echo $diff->format("Diferença de %y anos, %m meses e %d dias.");
echo $diff->format("Diferença total de %a dias"); 

example here: link

    
23.04.2015 / 19:08
1

Do not reinvent the wheel, use what you're ready for:

Use DateTime

$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "diferença" . $interval->y . " anos, " . $interval->m." meses, ".$interval->d." dias"; 

// mostrta o total de dias, nao dividido em anos e meses
echo "difference " . $interval->days . " days ";
    
23.04.2015 / 19:18