Search code examples
phparraysdateforeach

Date change function in PHP


I was using this to get date string with $caquantidadeparcelas (define number of dates), and $caprimeirovencimento (first date to reference), but cannot find why is not working as expected, can someone explain?

<?php
    function gerarDatasPagamento($dataInicialStr, $caquantidadeparcelas) {
        // Converte a string da data inicial para um objeto DateTime
        $caprimeirovencimento = new DateTime($dataInicialStr);
                    
        // Array para armazenar as datas de pagamento
        $datasPagamento = [];
                    
        // Adiciona a data inicial ao array
        $datasPagamento[] = $caprimeirovencimento->format('d-m-Y');
                    
        // Gera as datas subsequentes com um mês de diferença
        for ($i = 1; $i < $caquantidadeparcelas; $i++) {
            $caprimeirovencimento->modify('+1 month');
            $datasPagamento[] = $caprimeirovencimento->format('d-m-Y');
        }
                    
        return $datasPagamento;
    }

    $due_dates = gerarDatasPagamento($caprimeirovencimento, $caquantidadeparcelas);

    foreach ($due_dates as $index => $date) {
        echo ($index + 1) . "° vencimento: " . $date . "&nbsp;";
    } ?>

i tried to change function but the problem is in date format sometimes recognizes month as day, and eventually generates fatal error


Solution

  • It looks like you’re trying to handle an invalid date input in PHP. Below is the code you can consider:

    function generatePaymentDates($initialDateStr, $numberOfInstallments) {
        $format = 'd-m-Y';
        $firstDueDate = DateTime::createFromFormat($format, $initialDateStr);
    
        if (!$firstDueDate) {
            return "Invalid date provided. Make sure it is in the $format format.";
        }
    
        $paymentDates = [];
        $paymentDates[] = $firstDueDate->format($format);
    
        for ($i = 1; $i < $numberOfInstallments; $i++) {
            $firstDueDate->modify('+1 month');
            $paymentDates[] = $firstDueDate->format($format);
        }
    
        return $paymentDates;
    }
    
    $result = generatePaymentDates($firstDueDate, $numberOfInstallments);
    
    if (is_array($result)) {
        foreach ($result as $index => $date) {
            echo ($index + 1) . "° due date: " . $date . "&nbsp;";
        }
    } else {
        echo $result; // Display error message
    }