PHP: Week starts on Monday, but "monday this week" on a Sunday gets Monday next week

datetime, php

Solution

As far as I can tell, this is a bug. I see no logical reason why `strtotime('this week');` should return a future date. This is a pretty major bug. In my particular case, I had a leaderboard that showed the users with the most points since the beginning of the week. But on Sundays, it was empty because `strtotime` returned a timestamp for a future date. I was doubtful, because just I don't know how this could have gone unnoticed, but I couldn't find any other reports of this bug.

Thanks for all your time and help, folks.

Problem

Here's a summary of the issue: On Sundays, `strtotime('this week')` returns the start of next week. In PHP, the week seems to start on Monday. But, on any day except Sunday, this code ``` echo date('Y-m-d', strtotime('monday this week', strtotime('last sunday'))); ``` Outputs the date of this week's Monday, when it seems like it should be outputting last weeks Monday. It seems like, in this case, PHP is treating both Sunday and Monday as the the start of the week. It's now Monday, Dec 10, 2012, or 2012-12-10. `date('Y-m-d', strtotime('sunday last week'))` returns `2012-12-09` - yesterday. Is this a bug, or am I missing something? It seems like a bug this obvious should be fairly well known, but I can't find anything about it. Is the only way to get the start of the week to use some special handling for Sundays? ``` $week_offset = (int) 'sunday' == date('l'); $week_start = strtotime("-$week_offset monday"); // 1 or 0 Mondays ago ```

Original source