In my application a week is defined from Monday 12:00:00 AM to Sunday 11:59:59 PM
Whenever a user visits my site - I need to find the previous weeks date range and show him results based on that. It sounds simple but I'm lost.
To give you scenarios - - March 1st Monday 12:00:00 AM to March 7th Sunday 12:59:59 PM is the week.
Now when a user visits the website on 8th March or 10th March or 12th March - based on the current date I should be able to get the previous week date range ie start date March 1st and end date March 7th.
But if the user visits the site say on 16th March - the date range I would need is March 8th to March 15th.
How can I do this in PHP. Thanks
You could try doing it with timestamps, but that gets messy with timezone changes (for example, CET -> CEST). I'd use the DateTime
class:
$d = new DateTime();
$weekday = $d->format('w');
$diff = 7 + ($weekday == 0 ? 6 : $weekday - 1); // Monday=0, Sunday=6
$d->modify("-$diff day");
echo $d->format('Y-m-d') . ' - ';
$d->modify('+6 day');
echo $d->format('Y-m-d');
The strtotime
function is very handy here:
$mondayStr = "last monday";
if (date('N') !== '1') { // it's not Monday today
$mondayStr .= " last week";
}
$monday = strtotime($mondayStr);
echo date('r', $monday); // Mon, 22 Feb 2010 00:00:00 +1000
$sunday = strtotime('next monday', $monday) - 1;
echo date('r', $sunday); // Sun, 28 Feb 2010 23:59:59 +1000
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With