Reputation: 568
Say I wanted to get the week beginning and ending, for example:
Mon 29th June - week start
Sun 5th July - week end
and then tomorrow (Mon 6th July) it will say:
Mon 6th July - week start
Sun 12th July - week end
Is this the right way to do it?
$week_start = date('Y-m-d', strtotime('last monday'));
$week_end = date('Y-m-d', strtotime('this sunday'));
Upvotes: 2
Views: 97
Reputation: 43552
DateTime class has this nice method called setIsoDate()
:
$start = new DateTime();
$start->setIsoDate($start->format('o'), $start->format('W'));
$end = clone $start;
$end->modify('+6 day');
echo "From: " . $start->format('Y-m-d') . " to: " . $end->format('Y-m-d');
Upvotes: 1
Reputation: 7930
That would not work properly if the current date is Monday. last monday
would then translate to the Monday the previous week.
I would use this syntax instead:
$week_start = date('Y-m-d', strtotime('last monday', strtotime('tomorrow')));
$week_end = date('Y-m-d', strtotime('this sunday'));
You might also consider avoiding those "advanced" relative formats, and seek the correct dates based on the current weekday. Might be a bit more reliable, as those week formats don't always seem to behave as one might expect, and the logic behind them isn't readily available.
This solution uses simpler strtotime
formats, and instead puts the seek logic in the code itself. As such, it's a lot more predictable, if a little less elegant.
$weekday = date("N"); // 1 = Monday, 7 = Sunday
$week_start = date("Y-m-d", strtotime("-" . ($weekday - 1) . " days"));
$week_end = date("Y-m-d", strtotime("+" . (7 - $weekday) . " days"));
Note that the date("N")
flag is only available in PHP 5.1 and later. For older version you'd need to use date("w")
, and move the Sunday value to the back.
$weekday = date("w"); // 0 = Sunday, 6 = Saturday
if ($weekday == 0) {
$weekday = 7;
}
Upvotes: 0