Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

strange Datetime::setDate() behaviour

Tags:

php

datetime

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?

like image 829
Ryo Avatar asked Apr 01 '16 09:04

Ryo


1 Answers

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
)
*/
like image 124
Ryo Avatar answered Oct 01 '22 06:10

Ryo