简体   繁体   English

奇怪的Datetime :: setDate()行为

[英]strange Datetime::setDate() behaviour

I need a little help to look for any possible misconfiguration of the server or php, because I have a strange behaviour of DateTime's "setDate" method: 我需要一些帮助来寻找服务器或php的任何可能的错误配置,因为我有一个DateTime的“setDate”方法的奇怪行为:

$datetime = new DateTime('2016-01-01 23:59:59');
$datetime->setDate(2016, 2, 28);
print_r($datetime);

/*
DateTime Object
(
    [date] => 2016-01-28 23:59:59
    [timezone_type] => 3
    [timezone] => Europe/Berlin
)
date should actually be february!
*/

Well, at least it is consistent, because, when I set date to march (3) the result is february (2). 好吧,至少它是一致的,因为,当我将日期设定为3月(3)时,结果是2月(2)。

$datetime = new DateTime('2016-01-01 23:59:59');
$datetime->setDate(2016, 3, 28);
print_r($datetime);

/*
DateTime Object
(
    [date] => 2016-02-28 23:59:59
    [timezone_type] => 3
    [timezone] => Europe/Berlin
)
date should actually be march!
*/

In PHP default timezone is set 在PHP中设置默认时区

// "Europe/Berlin"
echo date_default_timezone_get();

The Server is currently running with 服务器当前正在运行

php version 5.3.2 (unfortunately i cannot upgrade)

Server time is set accurately and the timezone is also Europe/Berlin. 服务器时间准确设置,时区也是欧洲/柏林。

Can someone please help me / advice me what I could do or check else? 有人可以帮助我/建议我能做什么或检查其他吗?

As for the strange behavior I found a strange workaround. 至于奇怪的行为,我发现了一个奇怪的解决方法。 I think and hope others won't get this error (see answers to the question), but just in case: 我想并希望别人不会得到这个错误(请参阅问题的答案),但以防万一:

You need to re-instantiate the DateTime-Class to the variable. 您需要将DateTime-Class重新实例化为变量。 Please don't ask me why! 请不要问我为什么! f-,- F-,-

$datetime = new DateTime();
$datetime = new DateTime('2016-01-01 23:59:59');

$datetime->setDate(2016, 2, 28);
print_r($datetime);

/*
DateTime Object
(
    [date] => 2016-02-28 23:59:59
    [timezone_type] => 3
    [timezone] => Europe/Berlin
)
*/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM