Figuring the Start of the Week with PHP

I have a time keeping utility written in PHP and MySQL. To make a query of the hours recorded so far in a given week, I needed to determine the start date of the week, in the MySQL format of ‘YYYY-MM-DD HH:MM:SS’. I had been using this code:

date('Y-m-d H:i:s’, mktime(0, 0, 0, date(’m’), date(’d’)-date('w’), date('Y’)));

It was successfully giving me midnight on Sunday for my code. Until the change to daylight savings time reared its ugly head (why can’t we stay on DST all year?). This week that piece of code gave me '2006-04-01 23:00:00’, so the rest of my code decided to include some time from Saturday.

I worked through a couple variants, but settled on this replacement:

date('Y-m-d’, mktime(1, 0, 0, date(’m’), date(’d’)-date('w’), date('Y’))) . ’ 00:00:00’;

This code adds an hour to the time computation. So the errant Saturday at 11PM gets returned to Sunday at midnight. Other weeks will show 1AM, and the switch back to standard time might show 2AM. Since I always want midnight, the simplest thing seemed to be to drop the time off the date function output entirely and just set it to midnight in the string.