PHP-Function to get the first date of a week

Issue

I have a question.

I tried this code to get the first date of a week.
It works but only when the number has two digits.

So when the weeknumber is 10 it works but when the weeknumber is 9 or 09 it doesn’t.
Does anyone here know the error?

$year =2022;
$weeknr = 10;  

$timestamp = strtotime("{$year}-W{$weeknr}");

var_dump($timestamp);
var_dump(date ("d-m-Y", $timestamp));

Solution

Quote your weeknr,
date("W", $timestamp); returns string

$year = 2022;
$weeknr = "07";  // must be string

$timestamp = strtotime("{$year}-W{$weeknr}");

var_dump($timestamp);
var_dump(date ("d-m-Y", $timestamp));

result:

int(1644796800)
string(10) "14-02-2022"

Answered By – benkov

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published