Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/date/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
PHP日期函数工作不正确,日期可追溯到1970年_Php_Date_Datetime - Fatal编程技术网

PHP日期函数工作不正确,日期可追溯到1970年

PHP日期函数工作不正确,日期可追溯到1970年,php,date,datetime,Php,Date,Datetime,这是我的功能 public function test($input, $duration){ $input = date_create($input); $month = date_format($input,'m-Y'); $monthsArray[] = array( 'month' => $month, ); for($i=0; $i<$durati

这是我的功能

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);
    }
结果应该是这样,

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

但是这个函数返回

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


输入日期的格式无效,并且需要用引号括起来,因为它标识字符串。否则,您将从5中减去2016。如果要使用m-Y格式,则需要使用
DateTime::createFromFormat()
来解析该日期:

<?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);

您的输入日期格式无效,还需要用引号括起来,因为它标识字符串。否则,您将从5中减去2016。如果要使用m-Y格式,则需要使用
DateTime::createFromFormat()
来解析该日期:

<?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);
您可以这样使用

<?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);
?>

检查此处:

您可以这样使用

<?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);
?>


检查此处:

date函数返回1970年1月1日,当您输入的日期无效时。(阅读文档)。所以,从这里开始。绝对确保传递的是有效日期,而不是类似于
05-2016
,实际上是
-2011
。当输入的日期不是有效日期时,日期函数返回1970年1月1日。(阅读文档)。所以,从这里开始。绝对确保传递的是有效日期,而不是像
05-2016
那样的日期,实际上是
-2011