PHP - date function - search for the previous week

In my application, the week is determined from Monday 12:00:00 to Sunday 11:59:59 PM

Whenever a user visits my site, I need to find the date range of the previous weeks and show its results based on this. It sounds simple, but I'm lost.

To give you the scripts - - March 1st Monday 12:00:00 AM to March 7th Sunday 12:59:59 PM - week.

Now, when the user visits the website on March 8 or March 10 or March 12 - based on the current date, I should be able to get the date range of the previous week, i.e. the start date is March 1 and the end date is March 7.

But if the user visits the site, they say March 16 - the date range that I need is from March 8 to March 15.

How can I do this in PHP. Thanks

+5
source share
5 answers

You can try to do this with timestamps, but it gets messy with time zone changes (e.g. CET -> CEST). I would use a class DateTime:

$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');
+8
source

The function is strtotimevery convenient here:

$mondayStr = "last monday";
if (date('N') !== '1') {  // it 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
+8
source
function get_week_start($year, $month, $day)
{
    $timestamp = mktime(0, 0, 0, $month, $day, $year);
    return date('F j Y', $timestamp = mktime(0, 0, 0, $month, date('d', $timestamp)-date('w', $timestamp), $year));
}

Perhaps you can add the next 6 days, and you have it.

+1
source

There is a user function for this in the PHP Documentation .

+1
source

GMT version

$prev_monday_t = time() - (gmdate('N') + 6) * 86400;
$prev_sunday_t = time() - gmdate('N') * 86400;

echo gmdate('Y-m-d H:i:s', $prev_monday_t ).' '.gmdate('Y-m-d H:i:s', $prev_sunday_t );

Local version

$prev_monday_t = time() - (date('N') + 6) * 86400;
$prev_sunday_t = time() - date('N') * 86400;

echo date('Y-m-d H:i:s', $prev_monday_t ).' '.date('Y-m-d H:i:s', $prev_sunday_t );
0
source

All Articles