If you find yourself working on a project that deals with dates – for example a calendar or an accounting package – you may need to determine the time at the start of the current week. While there are several ways to do this, the following one-liner will give the necessary value:
$result = mktime(0, 0, 0, date(“m”), date(“d”), date(“Y”)) – ((strftime(“%u”) == 7) ? 0 : (86400 * strftime(“%u”)));
With such a complex statement, a little explanation is in order. Let’s start with strftime(“%u”). This expression gives the current day of the week as an integer in the range of 1 to 7, with 1 representing Monday and 7 representing Sunday, e.g. on Thursday strftime(“%u”) would return 4. This format adheres to an ISO standard, but is awkward to those of us who consider Sunday to be the first day of the week.
We use the current position in the week to determine how many days have elapsed since the most recent Sunday (if today is a Sunday, that value is 0; if today is Wednesday, that value is 3, and so on). We can then subtract that many days – at 86400 seconds apiece – from the timestamp for midnight of the current day. The result is the timestamp for midnight on the first day of this week.