2013-09-24

ISO 8601 week dates

London, UK

Tuesday, September 24th 2013, 09:15 BST

Back in 2009 I wrote that PHP calendar implementation uses the ISO 8601 calendar for year numbers. In the past few weeks I've seen a few bug reports in the PHP bug system (65694 and 65730) that deal with another aspect of this same calendar: week numbers.

Week numbers are defined in this same ISO 8601 standard. Each year has 52 or 53 weeks and weeks always start on a Monday. Week number 1 of each year is the first week in a year that has the first Thursday of the year, or in other words, the week containing January 4th.

With the year number (2012, 2013, etc), the week number (01-53) and the day number (1-31) you can described a day. PHP supports the formats yyyy "W" ww
d where yyyy is the ISO 8601 year, "W" a delimiter, ww the week number and d the day of the week (with 1 being Monday, and 7 being Sunday). It is also possible to omit the day-of-week (yyyy "W" ww) to represent the start of the week (Monday) and to add - in the format (such as in yyyy "-W" ww "-" d. Examples are: 2013-W39-2 for today and 2013-W40 for next Monday.

Tuesday January 1st, 2013 is represented as 2013-W01-2, and Tuesday December 31st, 2013 as 2014-W01-2. As you see with December 31st, the ISO 8601 year (2014) is not the same as the calendar year (2013). The ISO year starts with (ISO) week 1, day 1, which is always a Monday. If you do the following in PHP, you get an unexpected answer:

Which outputs 2013-W01-2. The Y format specifier gives the calendar year which is not the same as the ISO 8601 year. To show the ISO 8601 year, you need to use the o specifier. See the following:

This outputs:

Parsing an ISO year/week/day combination displays the same issues:

Which outputs 2013-12-31. The ISO week date 2014-W01-2 is part of calendar year 2013.

In most ISO 8601 years, there are 52 weeks. But once in a while, there are 53. This is because a year is 52 weeks and one day (or two days for leap years). In every 400 years there are 71 years with 53 weeks (and 329 years with 52 weeks). The next year for which the ISO year has 53 weeks is 2015:

Week 53 in ISO year 2015 goes from Monday 2015-12-28 to Sunday
2016-01-03. In 2018 the ISO year and calendar year start on the same date— 2018-01-01 or 2018-W01-1.

As conlusion, this article shows that there are two ways representing dates in PHP. In the Gregorian1 calendar with year, month and day (of month), and in the ISO 8601 calendar with year, week and day (of week). The format characters for the two different years are either Y or o and they should not be confused.



Truncated by Planet PHP, read more at the original (another 514 bytes)

Show more