Default date to maturity - PHP

Asked

Viewed 615 times

3

I’ve researched this issue here at the portal, and although there are similar questions, I haven’t found anything in the sense I need. On google also found nothing that exactly assists in my problem.

Based on the date of the first instalment, I need to automatically calculate the due date of n installments, these being the fixed day for all of them.

Example:

First instalment: 25/09/2016

By incrementing 30 days to this date, the due date for each month may vary according to the size of the month. In addition, it may happen that some month is "skipped", as in the month of February.

So then, I need him to do something down:

First instalment: 30/01/2016

The second instalment should be: 29/2/2016 The third instalment should be: 30/03/2016 The fourth installment should be: 30/04/2016 And so on and so forth.

What do you say? Can you assist me in this matter? Any suggestion is welcome.

Abçs

1 answer

3

It would be a logic to always check the generated date is valid:

<?php

function parcelas($data, $numero)
{
    $parc = array();
    $parc[] = $data;
    list($dia, $mes, $ano) = explode("/", $data);
    for($i = 1; $i < $numero;$i++)
    {
        $mes++;
        if ((int)$mes == 13)
        {
            $ano++;
            $mes = 1;
        }
        $tira = $dia;
        while (!checkdate($mes, $tira, $ano))
        {
            $tira--;
        }
        $parc[] = sprintf("%02d/%02d/%s", $tira, $mes, $ano);
    }
    return $parc;
}


$data = "29/01/2015";

var_dump(parcelas($data, 13));

Example

  • 1

    Hello Virgilio. That’s exactly what I needed! Thank you very much.

Browser other questions tagged

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