简体   繁体   中英

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:

$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).

$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

// "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. Please don't ask me why! 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
)
*/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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