-1

I saw this code here on stack overflow

    function add($date_str, ${
    $date = new DateTime($date_str);
    $start_day = $date->format('j');

    $date->modify("+{$months} month");
    $end_day = $date->format('j');

    if ($start_day != $end_day)
        $date->modify('last day of last month');

    return $date;
}

$result = add('2011-01-28', 1);  // 2011-02-28
$result = add('2011-01-31', 3);  // 2011-04-30

Which increments the date but does not exceed the last day of the month. But when i try to run the function using

$dues=add('2011-01-28', 1); echo $dues;

It returns an "Object of class DateTime could not be converted to string" error? But it seems that it works for other people.

Original link

Community
  • 1
  • 1
Mike
  • 19
  • 3
  • 1
    There is syntax error in the first row: `function add($date_str, ${`. Missing second var name and bracket. – pavel Feb 14 '15 at 06:10

3 Answers3

0

The first row of your code has to be:

function add($date_str, $months) {

You have there syntax error.

pavel
  • 26,538
  • 10
  • 45
  • 61
0

Format of function is not right. Use the code below

function add($date_str, $months){
    $date = new DateTime($date_str);
    $start_day = $date->format('j');

    $date->modify("+{$months} month");
    $end_day = $date->format('j');

    if ($start_day != $end_day)
        $date->modify('last day of last month');

    return $date;
}

$result = add('2011-01-28', 1);  // 2011-02-28
$result = add('2011-01-31', 3);  // 2011-04-30

Hope this helps you

Utkarsh Dixit
  • 4,267
  • 3
  • 15
  • 38
-3

All I had to do was to use $dues->format('Y-m-d')

Taifun
  • 6,165
  • 17
  • 60
  • 188
Mike
  • 19
  • 3