phpdatestrtotime

How can I add a number of days after an end of the month in PHP?


My goal is to print a dueDate. The due date formula is end of the month adding the days which is 7 on my example. How can I make it possible? My echoed value on my actual result is "Due date: 08/01/1970" My expected result is "Due date: 07/06/2018"

$invoice_date = "11/05/2018";
$days  = 7;
$is_invoice = false;

$date = date("d/m/Y", strtotime($invoice_date));

if ($is_invoice) {
    $dueDate = date('d/m/Y', strtotime("+$day $days", strtotime($date)));
} else {
    $dueDate = date('t/m/Y', strtotime($date));
    $dueDate = date('d/m/Y', strtotime("+$day days", strtotime($date)));
}

echo "Due date: $dueDate";

Thanks in advance for the help


Solution

  • Try with the DateTime class:

    $date = DateTime::createFromFormat('d/m/Y', '11/05/2018');
    
    $dueDate = clone $date;
    $dueDate->modify('+7 days');
    
    echo 'Date : ' . $date->format('d/m/Y') . "\n";
    echo 'Due  : ' . $dueDate->format('d/m/Y') . "\n";
    

    Output:

    Date : 11/05/2018 
    Due : 18/05/2018
    

    See it here: https://3v4l.org/BjUSK