Handling different dates and timezones in an application is - like most aspects of i18n - very annoying (to put it mildly)… Recently we discovered the following behaviour at work…
If you create a DateTime object like this (in the current stable version of php, 5.2.3):
<?php
$oDateTest = new DateTime("@0", new DateTimeZone(date_default_timezone_get()));
echo "tz: ".$oDateTest->getTimezone()->getName()."\n";
echo "date: ". $oDateTest->format("Y-m-d H:i:s")."\n";
?>
It will be in the default timezone (’Europe/Berlin’ in my case) but say the date is 1970-01-01 00:00. This is wrong. The Unix timestamp “0″ stands for that exact date, but in another timezone: UTC. It should be 01:00 in Berlin.
This bug was reported multiple times, but with sometimes confusing bug reports. But someone had managed to submit a clear bug report with code to reproduce the behaviour (PHP Bug 43003) and the php developers acknowledged the bug and issued a fix that i verified to be (at least) in the following snapshots: php5.2-200803111530 and php5.3-200803111530.
Sadly, this fix is at best “unintuitive”, maybe it even qualifies as “still broken”. The above code gives the following output in these snapshots:
tz: +00:00
date: 1970-01-01 00:00:00
So, the DateTime object now knows that UNIX timestamps always are given in UTC and sets it’s timezone accordingly. But is this what it should do in this case? I - the programmer - clearly stated i wanted the DateTime object to be in my default timezone! Even if i explicitly give the timezone as ‘Europe/Berlin’ during construction, the object’s timezone still is UTC afterwards.
So instead of knowing that i have to manually set the DateTime to UTC, then back to my desired timezone when working with an UNIX timestamp i now have to know that a DateTime will be in UTC after setting it up with a UNIX timestamp. Personally i hate having to know things, IMHO it’s a sign of weak design. The API has to be clear, i don’t give a rat’s backside about the inner workings and struggles of the objects i use.
We went from this:
// FIXME: DateTime issue... needs the conversion to and from UTC...
$oDateTest = new DateTime("@0", new DateTimeZone('UTC'));
$oDateTest->setTimezone(new DateTimeZone("Europe/Berlin"));
To this:
// FIXME: DateTime issue... will always be UTC afterwards...
$oDateTest = new DateTime("@0", new DateTimeZone('Europe/Berlin')); // or UTC, or what/ever....
$oDateTest->setTimezone(new DateTimeZone("Europe/Berlin"));
Is this better or worse?
Entries (RSS)