Paulo Cunha
Paulo Cunha

Reputation: 47

What is wrong with this procedure to add 4 years to a date?

I am trying to add 4 years to a string with a date format from South America. I tried the bellow code:

date_default_timezone_set('America/Sao_Paulo');
$date_string = '10/10/2014';
$date = date_create($date_string);
$date_us_string = date_format($date, 'Y-m-d');
$date2_us = strtotime('+4 year', $date_us_string);
$date2_string = date_format($date2_us, 'd/m/Y');

But it isnt working and I dont know why. Anybody can help me?

Upvotes: 1

Views: 90

Answers (2)

Paulo Cunha
Paulo Cunha

Reputation: 47

Just for curiosity, this also works:

$date_string = '30/10/2014';
$date_string = explode("/", $date_string);
$date_string = date('m/d/Y', mktime(0, 0, 0, $date_string[1], $date_string[0], $date_string[2]) );

function makeDate($date, $days, $mounths, $years){
    $date = date('d/m/Y', strtotime($date));
    $date = explode("/", $date);
    return date('d/m/Y', mktime(0, 0, 0, $date[1] + $mounths, $date[0] +  $days, $date[2] + $years) );
        }
        $dateadded = makeDate($date_string, 0, 0, 4);
        echo $dateadded;

DEMO

Upvotes: 0

John Conde
John Conde

Reputation: 219864

PHP should be showing you an error. If not, you need to turn error reporting on. Here is the error:

Warning: date_format() expects parameter 1 to be DateTimeInterface, null given

This is because that function only works with DateTime() objects. You are not using them throughout your code which is causing even more errors before you get this far. Here is working code that is simpler (and uses DateTime() throughout):

$date_string = '10/10/2014';
$date = new DateTime($date_string, new DateTimeZone('America/Sao_Paulo'));
$date->modify('+4 years');
echo $date->format('d/m/Y');

Upvotes: 4

Related Questions