Salman Asmat
Salman Asmat

Reputation: 44

PHP DATE function not working correct and date goes back to 1970

Here is my function

public function test($input, $duration){

        $input = date_create($input);
        $month =  date_format($input,'m-Y');

        $monthsArray[] = array(
                'month' => $month,
            );

        for($i=0; $i<$duration; $i++){

            $monthsArray[]= array(

                'month' => date('m-Y', strtotime("$i months", strtotime($month))),

                );
        }

        var_dump($monthsArray);
    }

Here is my input,

test(05-2016,3);

result should be like this,

05-2016 06-2016 07-2016 08-2016

But this function returns

05-2016 01-1970 02-1970 03-1970

Upvotes: 0

Views: 110

Answers (2)

John Conde
John Conde

Reputation: 219874

Your input date is not in a valid format and also needs to be wrapped in quotes since it ids a string. otherwise you are subtracting 2016 from 5. If you are going to use the m-Y format you need to use DateTime::createFromFormat() to parse that date:

<?php

function test($input, $duration){

    $date= DateTime::createFromFormat('m-Y', $input);
    $monthsArray = [$input];

    for($i=0; $i<$duration; $i++){
         $date->modify('+1 month');
         $monthsArray[] = $date->format('m-Y');
    }

    var_dump($monthsArray);
}

test('05-2016',3);

Demo

I removed your usage of strtotime() as it is not needed or recommended for date manipulation.

Also, keep in mind that this code will break at the end of the month due to the fact that not all months have 30 or 31 days.

Upvotes: 2

Niklesh Raut
Niklesh Raut

Reputation: 34914

Your can use like this

<?php
function test($dt,$months){
  echo "\n".$dt;
  for($i=1;$i<=$months;$i++){
    $increseby =  "+"."$i";
    echo "\n".date('m-Y',strtotime('1-'.$dt." $increseby month"));
  }
}
test('05-2016',3);
?>

Check here : https://eval.in/570870

Upvotes: 1

Related Questions