Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Date function - finding the previous week

Tags:

date

php

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

like image 765
Gublooo Avatar asked Mar 02 '10 06:03

Gublooo


2 Answers

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');
like image 167
Lukáš Lalinský Avatar answered Oct 09 '22 16:10

Lukáš Lalinský


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
like image 20
nickf Avatar answered Oct 09 '22 16:10

nickf