Sebastian Td
Sebastian Td

Reputation: 184

Can someone explain this weird behaviour in PHP strtotime

I am working on a calendar function that should output the name of the week and the date where I have the weeknumber and year

The code works fine when the year is 2018, but as soon as it is 2019, something goes wrong

echo date("Y-m-d D", strtotime("monday 2018W37")); // outputs 2018-09-10 Mon
echo date("Y-m-d D", strtotime("monday 2019W37")); // outputs 2019-09-15 Sun

But if you check a valid calendar, a monday in week 37 2019 is of cause a monday and the date is 2019-09-09

Can someone explain this behaviour and maybe provide an alternative to strtotime.

Upvotes: 3

Views: 45

Answers (2)

LF-DevJourney
LF-DevJourney

Reputation: 28529

You should write it like this,

echo date("Y-m-d D", strtotime("2018W37")) . "\n"; // outputs 2018-09-10 Mon
echo date("Y-m-d D", strtotime("2019W37")) . "\n"; // outputs 2019-09-9 Mon

or

echo date("Y-m-d D", strtotime("2018W37-1")) . "\n"; // outputs 2018-09-10 Mon
echo date("Y-m-d D", strtotime("2019W37-1")) . "\n"; // outputs 2019-09-9 Mon

Upvotes: 3

Jay Blanchard
Jay Blanchard

Reputation: 34416

You should not have to specify "Monday" in the string, so use:

echo date("Y-m-d D", strtotime("2018W37")); 
echo date("Y-m-d D", strtotime("2019W37"));

Which returns:

2018-09-10 Mon
2019-09-09 Mon

Upvotes: 2

Related Questions