从DateTime减去天数

时间:2015-01-08 01:22:43

标签: php datetime

我会切到这里追逐。这是我的功能失调代码,它通过从结束时间中减去间隔来查找开始时间:

    $timeEnd = "2015-01-08T12:53:13-05:00"; //retrieved from bot crawler
    $interval = date_interval_create_from_date_string("10 days");
    $timeEndOb = new DateTime($timeEnd);
    $timeStartOb = $timeEndOb->sub($interval);
    $timeStart = $timeStartOb->format('Y-m-d H:i:s');
    echo $timeStart;
    //echoing 2015-01-08 12:53:13

我的愚蠢问题是什么?

2 个答案:

答案 0 :(得分:1)

您可以使用clone克隆对象:

$timeEnd = '2015-01-08T12:53:13-05:00';
$timeEndOb = new DateTime($timeEnd);
$timeStartOb = clone $timeEndOb;
$timeStartOb->modify('-10 days');
echo $timeStart = $timeStartOb->format('c');

demo

或者您可以使用DateTimeImmutable PHP> = 5.5.0 类,其行为与DateTime相同,但它从不修改自身但返回一个新对象:

$timeEnd = '2015-01-08T12:53:13-05:00';
$timeEndOb = new DateTimeImmutable($timeEnd);
$timeStartOb = $timeEndOb->modify('-10 days');
echo $timeStart = $timeStartOb->format('c');

demo

答案 1 :(得分:0)

您只需使用strtotime功能和date功能

即可
$timestamp_end = strtotime("2015-01-08T12:53:13");// Note, I removed the timezone
$date_start = date('Y-m-d H:i:s', strtotime('-10 days', $timestamp_end));
$date_end = date('Y-m-d H:i:s', $timestamp_end);
echo $date_start.' to '.$date_end;

2014-12-29 12:53:13 to 2015-01-08 12:53:13