0

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));
  • Use `sprintf()` to make sure it's always two digits? – droopsnoot Jun 13 '22 at 07:46
  • Does this answer your question? [PHP get start and end date of a week by weeknumber](https://stackoverflow.com/questions/4861384/php-get-start-and-end-date-of-a-week-by-weeknumber) – nice_dev Jun 13 '22 at 07:47

1 Answers1

2

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"
benkov
  • 184
  • 9
  • Oh jesus. Yes! But interessting, that it works with 10 without "". Okay, but no it's clear. It's a nice functions – maximiliansport Jun 13 '22 at 08:15
  • if the weeknumber is lower than 10 date("W") returns the weeknumber with zero (eg 07, 08), if you dont quote it when you type 07 it gets iits integer value eg (7) – benkov Jun 13 '22 at 08:43