The problem is that when you assign an object to a variable, it is assigned by reference. So when you do:
$date_past = $date_now->sub(new DateInterval("PT12H"));
The variables $date_past
and $date_now
both point to exactly the same reference and when you modify one, you modify both. You will notice this if you simply echo out the variables:
$date_now = new DateTime;
$date_past = $date_now->sub(new DateInterval("PT12H"));
echo $date_now->format('c'); // 2014-03-10T00:38:56-06:00
echo $date_past->format('c'); // 2014-03-10T00:38:56-06:00
Notice how they both print exactly the same thing. Normally what you want to do is use clone
:
$date_past = clone $date_now;
$date_past->sub(new DateInterval("PT12H"));
echo $date_now->format('c'); // 2014-03-10T12:41:20-06:00
echo $date_past->format('c'); // 2014-03-10T00:41:20-06:00