Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/235.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

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 DateTime对象生成不正确的结果_Php_Date_Datetime - Fatal编程技术网

Php DateTime对象生成不正确的结果

Php DateTime对象生成不正确的结果,php,date,datetime,Php,Date,Datetime,我正在尝试使用PHP中的DateTime对象创建开始日期和结束日期,以执行一些计算。我目前生成的日期如下: $end = new DateTime(date("Y-m-t 23:59:59", strtotime("last month"))); $start = new DateTime(date("Y-m-1 00:00:00", strtotime("-6 months", $end->getTimestamp()))); 这将给我一个上个月最后一天的结束日期和结束日期前六个月的第

我正在尝试使用PHP中的DateTime对象创建开始日期和结束日期,以执行一些计算。我目前生成的日期如下:

$end = new DateTime(date("Y-m-t 23:59:59", strtotime("last month")));
$start = new DateTime(date("Y-m-1 00:00:00", strtotime("-6 months", $end->getTimestamp())));
这将给我一个上个月最后一天的结束日期和结束日期前六个月的第一天的开始日期。我已经运行了一些测试,这为我提供了
2015-7-1
2015-12-31
的预期结果。但是,我尝试为结束日期指定不同的日期,但收到了错误的结果。以下是两个具体例子:

$end = new DateTime(date("Y-m-t 23:59:59", strtotime("now")));
$start = new DateTime(date("Y-m-1 00:00:00", strtotime("-6 months", $end->getTimestamp())));

$end = new DateTime(date("Y-2-t 23:59:59"));
$start = new DateTime(date("Y-m-1 00:00:00", strtotime("-6 months", $end->getTimestamp())));

第一个给了我一个开始日期
2015-7-1
,但正确地将
2016-1-31
作为结束日期,第二个给了我一个开始日期
2015-9-1
和结束日期
2016-3-2
。我到底做错了什么?我希望根据第一个代码段自动生成这些日期。

不要将新旧功能混用。您可以简单地使用interval方法,如下所示:

$dt = new DateTime; // now
$dt->modify('+6 months'); // add 6 months to 'now'
echo $dt->format('Y-m-t');

$dt->modify('-7 hours');
echo $dt->format('Y-m-t');

请参阅:

我不能只依赖一个对象。我需要第二种方法主要是为了执行一些计算(特别是两种方法之间的天数,我知道如何使用
diff
方法获得)。如何使用您显示的样式创建第二个对象?