lubosdz
lubosdz

Reputation: 4500

Why PHP returns 52nd week for 2017-01-01

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;
}

Upvotes: 0

Views: 237

Answers (1)

Jay Blanchard
Jay Blanchard

Reputation: 34426

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

Upvotes: 3

Related Questions