tzzz


ISO 8601 week number to date (timestamp) in PHP
August 14, 2006, 12:21 pm
Filed under: date, ISO8601, PHP, weekNumber

How do I convert an ISO 8601 week number to a timestamp or date?

Here’s a handy function for PHP that returns an array with seven timestamps, one for each day in week $weekNumber.

function getDaysInWeek ($weekNumber, $year) {
  // Count from '0104' because January 4th is always in week 1
  // (according to ISO 8601).
  $time = strtotime($year . '0104 +' . ($weekNumber - 1)
                    . ' weeks');
  // Get the time of the first day of the week
  $mondayTime = strtotime('-' . (date('w', $time) - 1) . ' days',
                          $time);
  // Get the times of days 0 -> 6
  $dayTimes = array ();
  for ($i = 0; $i < 7; ++$i) {
    $dayTimes[] = strtotime('+' . $i . ' days', $mondayTime);
  }
  // Return timestamps for mon-sun.
  return $dayTimes;
}

A simple way to test if it works:

$dayTimes = getDaysInWeek(33, 2006);
foreach ($dayTimes as $dayTime) {
  echo (strftime('%a %Y%m%d', $dayTime) . "n");
}

I had some trouble with making this work on my local computer. A good guess is that this has something to do with my locales, so beware! Run the test on the computer that hosts your application before you rely on it.