0

Why does following code return 2017-52 instead of expected 2017-01?

date('Y-W', strtotime('2017-01-01')); // returns "2017-52"

Edit: As explained here, there are rules applicable to the first week of the year. Unfortunatelly, this behaviour may cause date FROM to become greater than date TO. To fix this I use following code to calculate the week:

function getWeek($timestamp)
{
    $ts1 = mktime(0,0,0,1,1,date('Y', $timestamp));
    $ts2 = mktime(0,0,0,date('n', $timestamp),date('j', $timestamp),date('Y', $timestamp));
    $days = ceil(($ts2 - $ts1) / 86400);
    $week = ceil($days / 7);
    $yearWeek = date('Y', $timestamp).'-'.str_pad($week, 2, '0', STR_PAD_LEFT); // gives 2017-00 for January 1st
    return $yearWeek;
}
lubosdz
  • 4,210
  • 2
  • 29
  • 43
  • 3
    Because January 1 was a Sunday, the prior week (52) is the one returned. From the docs - *Wis theISO-8601 week number of year, weeks starting on Monday* – Jay Blanchard Jul 13 '17 at 21:31
  • Possible duplicate of [php get correct date by week one of the year using strtotime](https://stackoverflow.com/questions/27809736/php-get-correct-date-by-week-one-of-the-year-using-strtotime) – devlin carnate Jul 13 '17 at 21:37
  • So to ensure I will get 1st week `00` of the year, I must insert into timestamp at least 4th day in a week - e.g. `date('Y-W', strtotime('2017-01-05'));` returns correctly `2017-01`. – lubosdz Jul 13 '17 at 21:51

1 Answers1

3

Because January 1 was a Sunday, the prior week (52) is the one returned. From the docs - W is the ISO-8601 week number of year, weeks starting on Monday

enter image description here

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119