Wednesday, September 1, 2010

PHP: date() versus DateTime

Today I've stumbled upon an interesting bug in phps date() versus the DateTime object (since PHP 5.x). When writing unit test for an old view helper that creates parts of links from timestamps, I used DateTime::createFromFormat to create my expected values while using the view helper relied on date("d.m.Y") for it's return values.

When setting up the test, I choosed to use a data provider and just typed in long integers to represent my unix timestamps without thinking about a realistic length for them.

In the first step PHPunit confronted me with a typical result of the Y2K38 problem, since I had choosen a number (123557556123) which represents the 20th of May in the year 5885 :
1) onvLinkViewHelperTest::testCreatePortfolioChartDatesString with data set #5 (123557556123)
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-FROM=20.05.5885&TO=03.09.2010
+FROM=04.06.1938&TO=03.09.2010

I'll not describe this bug here, since it's fairly known around the blogs. I then decided to ignore the problem, because a colleague was just about to refactor the date view helpers who were responsible for the bug and doing a job twice thus having to merge both results doesn't sound too agile.

So I changed my data provider and randomliy choosed the number 12352343 as a date. Now I stumbled into another bug which in the first place made me think I've found a new bug in the DateTime object (or date() function).
1) onvLinkViewHelperTest::testCreatePortfolioChartDatesString with data set #4 (12352343)
Failed asserting that two strings are equal.
--- Expected
+++ Actual
@@ @@
-FROM=23.05.1970&TO=03.09.2010
+FROM=24.05.1970&TO=03.09.2010
When inspecting the behaviour I found out, that there were 2 hours of difference in time, which - in some of the provided data - lead to that the next day was returned as FROM and TO.

This is because there is a second difference in date()s and DateTime()s behaviour: DateTime will ignore your date_default_timezone_set setting.

Working with both, date() and DateTime() really seems complicated in an unnecessary fashion. I'd stick to the latter, because of the Y2K38 bug and because I prefer objects.

0 comments:

Post a Comment