开发者

Dates overwriting one another in php

开发者 https://www.devze.com 2023-02-05 22:04 出处:网络
Okay, so I\'m trying to get two variables. One with yesterday\'s date, one with a date six days from tod开发者_如何学编程ay. This is so I can query google calendar for events happening this week.

Okay, so I'm trying to get two variables. One with yesterday's date, one with a date six days from tod开发者_如何学编程ay. This is so I can query google calendar for events happening this week. I'm building a date time object, setting the date to today, then trying to store the values in two new variables. However, when I set the second variable, the first is getting modified as well. It appears to be assigning the variables by a reference to the object instead of the value I'm trying to stick into it.

$todayData = explode("-", date("Y-m-d", Time()));
//Get DateTime for Yesterday
$today = new DateTime();
$today->setDate($todayData[0], $todayData[1], $todayData[2]);
echo $today->format("Y-m-d");
echo "<br />";
//Yesterday
$startDate = $today->modify("-1 day");
echo $startDate->format("Y-m-d");
echo "<br />";
//End of the week
$endDate = $today->modify("+6 day");
echo $endDate->format("Y-m-d");
echo "<br />";

//recheck yesterday
echo $startDate->format("Y-m-d");


When you modify $today, you're modifying a reference to a newly created object. In turn, since $startDate and $endDate both reference $today, they are viewing the same object.

One solution is to return a new DateTime object each time you call the modify() method I assume you've created. This would then allow you to have a brand new date every time modify() is used, but then this wouldn't really modify the original DateTime object.

Another option is to use cloning in your object. This makes a new object with the same value as the object you're duplicating. See here: http://php.net/manual/en/language.oop5.cloning.php


As @Doug explained the reason why this isn't working is because $startDate and $endDate are referencing the same object.

Here's a quick solution: http://codepad.org/SKigfebO

Personally I wouldn't use the DateTime object. You can do this kind of operations using mktime:

$startDate = date('Y-m-d', mktime(date('H'), date('i'), date('s'), date('n'), date('j') - 1, date('Y')));
$endDate = date('Y-m-d', mktime(date('H'), date('i'), date('s'), date('n'), date('j') + 6, date('Y')));
0

精彩评论

暂无评论...
验证码 换一张
取 消