Search code examples
phpdatefpdf

How to fix Uncaught Error: Call to a member function add() on string


Am trying to print the date to pdf using fpdf library, but there is an error.

$date = date("F j, Y");
$date->add(new DateInterval('P14D'));
$this->Cell(185, 5, 'Due Date: '.date_format($date, 'Y-m-d'), 0, 0, 'R');

I need to add 14 days to the current date and print


Solution

  • You are mixing procedural date() functions and DateTime objects. If you want to use DateTime objects, then do

    $date = new DateTime;
    $date->add(new DateInterval('P14D'));
    $this->Cell(185, 5, 'Due Date: '.($date->format('Y-m-d')), 0, 0, 'R');
    

    You can also use the +14 days string and just create the object 14 days ahead of today,

    $date = new DateTime("+14 days");
    $this->Cell(185, 5, 'Due Date: '.($date->format('Y-m-d')), 0, 0, 'R');
    

    Or if you want to stick with procedural date(),

    $date = date("Y-m-d", strtotime("+14 days"));
    $this->Cell(185, 5, 'Due Date: '.$date, 0, 0, 'R');