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

Asked

Viewed 1,198 times

1

I have a algorítimo done in C but I decided to do in PHP. The 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 on a line, the last line contains the negative day number

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

I’ve come this far:

<?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 someone help me solve this problem?

  • From a look here -> http://blog.thiagobelem.net/calculando-a-diferenca-em-dias-entre-duas-dates/

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: http://ideone.com/IaTyIj

  • It’s because in his case he would have to do this algorithm in c++ and portugol, I was trying to do in php to explain the algorithm to him.

  • Then write the logic in Portugol and then go to c++

  • In this algorithm I have to take the dates and show the days from one date to another, and not like this.

1

Do not invent the wheel, use what you have ready:

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 ";
  • 1

    It’s because in his case he would have to do this algorithm in c++ and portugol, I was trying to do in php to explain the algorithm to him.

  • I get it Samuel, in this case it might be better to try doing it in C anyway

  • In this algorithm I have to take the dates and show the days from one date to another, and not like this.

Browser other questions tagged

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