TAGS :Viewed: 9 - Published at: a few seconds ago

[ date/gmdate returns wrong week number ]

I'm using a time-based token using as seed the year and the number of week, example:

$token = md5($salt + gmdate('YW'));

Yesterday sunday the token got broken, the time on server and client was synced (on time).

Checking with the interactive cli tool of php, I realized the number of week returned by PHP is "01" (zero-one).


Interactive mode enabled

php > echo gmdate('W');
01php > echo date('W');
01php > 

At the moment of this post, it is 29-dec at 21:58 UTC (9:58 pm) and this was broken since yesterday at 00:00 UTC.

Tested on php 5.5.9

Answer 1

Instead of format character Y, use o, which will return ISO-8601 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 PHP 5.1.0)


echo gmdate('oW');

Answer 2

Probably due to different timezone or locale settings. In some countries/standards sunday is considered as the first day of the week.


date = a date value. mode = An integer indicating the starting of the week.

The default arugment is 0 which is sunday, setting this to 1 will be monday, 2 tuesday and so on.


Quoted from How do I set first day of the week to Monday when using Week(Date) in PHP/MySQL?

Answer 3

I found the problem.

In the ISO-8601 standar, this week is the 01 of 2015, and not the last of 2014. This can be check here:

The problem is, I on the client use a function returns 2015 and 1 (And I from PHP use 2014 and 01 "201401" !== "20151").