ISO Week and Year in PHP and PostgreSQL

The new year always brings with it a few small things that go bump in the morning. 2008 was no different. Intervals started behaving oddly on New Year’s Eve morning — the default timesheet was a year behind schedule. What happened?

In our code, we are using the week number of year, as specified on the PHP date function page, but we weren’t using for the year. The week number specifies the last monday of a year as the first week of the new year, if that new year begins before thursday. Intervals thought it was the first year of 2007!

In , the fix was as easy as converting all instances of date(’Y') to date(’o'), according to php.net:

year number. This has the same value as Y, except that if the ISO week number (W) belongs to the previous or next year, that year is used instead. (added in 5.1.0)

That fixed everything on the side of things. But next we had to dig into the queries and get them to use the ISO Year.

Snag.

PostgreSQL 8.2.5 doesn’t support ISO Year in the Extract function. EXTRACT(ISOYEAR, timestamp) is being included in 8.3, as specified here in the RC1 documentation. But 8.3 hasn’t been released yet, and we needed to fix things immediately.

Our final fix was to instead use the TO_CHAR(timestamp, ‘IYYY’) function. It’s not ideal to be using a string formatting function for data comparisons, because it slows down some of the queries. But we had to trade some performance to get things working properly again in the new year. As soon as the PostgreSQL developers release a stable version of 8.3, we’ll change our queries back to using EXTRACT(ISOYEAR, timestamp).

Tags: , , ,
Related posts
Bookmark: Post to Del.icio.us Post to Digg Post to Google Post to Ma.gnolia Post to MyWeb Post to Newsvine Post to Simpy Post to Slashdot Post to Technorati

One Response to “ISO Week and Year in PHP and PostgreSQL”

  1. Michael Says:

    http://www.kaltenbrunner.cc/blog/index.php?/archives/21-8.3-vs.-8.2-a-simple-benchmark.html

    Looks like 8.3 should be snappier as well.

Leave a Reply