PHP: Date from Week Number

» »

Here's how to get the first date of any week number using one single row of PHP code.

I've struggled to find a simple and effective solution to this problem, so finally I solved it myself. This is an easy-as-it-gets solution which requires only a single row of code in PHP.

Getting started

First things first. Let's declare our parameters for this test; I want to find out which date is the first of week 1 of the year 2020.

$year = 2020;
$week = 1;

As some of you may know, this date will actually not be in the year 2020, but in the year 2019 — and this is why this is such a weird thing to solve by yourself, since it has so many variables to take into account.

The function we will use to solve this is the date() and strtotime() functions, like this:

$date = date('Y-m-d',strtotime(2020W01));

The only thing wrong with our parameters is that the week we're using, 1, is not made of two digits, which the date() function needs to correctly translate the week into a date. Because of this, we also use the sprintf() to add a zerofill digit in front of the week number, but only when needed;

$week = sprintf("%02d",$week);

This translates "7" to "07", but we don't need it as a separate line — we can bake it in the final row of code.

The solution

Thus, our final function to get the week translated to a date is this;

$date = date('Y-m-d',strtotime($year.'W'.sprintf("%02d",$week)));

Seriousy — how great is this?