简体   繁体   中英

Get first day of current week - x

I need to get the first day of the week (Monday), 8 weeks back from today, where 8 is a variable.

What's the best way to do that in PHP?

You can make some math with dates in PHP like:

$now = date('F d, Y H:i');
$newdate = date('F d, Y H:i', strtotime($now.' - 8 weeks'));
echo $newdate;

In this case it will output a current date minus 8 weeks.

Also to count which day is today you can use:

$dw = date( "w", strtotime($newdate));

Where $dw will be 0 (for Sunday) through 6 (for Saturday) more informations can be found: PHP: date

Solution

In your case it would look as follows:

<?php
$weeks = 8;

$now = date('F d, Y H:i:s');
$newdate = date('F d, Y H:i:s', strtotime($now.' - '.$weeks.' weeks'));
$new_date_day = date( "w", strtotime($newdate));
$minus = $new_date_day - 1;

if ($minus < 0) { //check if sunday
    $plus = $minus * -1;
    $newdate = date('F d, Y H:i:s', strtotime($newdate.' + '.$plus.' days'));
} else {    
    $newdate = date('F d, Y H:i:s', strtotime($newdate.' - '.$minus.' days'));
}

echo $newdate;
?>

Of course you can echo what ever style of date you want. F.ex. F d, YH:i:s will output November 28, 2016 06:18:03 .

$weeks = 8;

// Timestamp for $weeks weeks ago
$time = strtotime("$weeks weeks ago");

// Day of the week for $time (1 - Mon, ...)
$week_day = date('N', $time);

// Number of days from Monday
$diff = $week_day - 1;

// The date of the Monday $weeks weeks ago
echo date('j', $time - ($diff * 24 * 3600));

It's not really complicated actually, all you got to do is play a little bit with datetimes ;

<?php
$dt = new Datetime(sprintf('%d weeks ago', 8)); // replace 8 with variable, your value, whatever
$day = $dt->format('w');
$dt->modify(sprintf('%d days go', ($day - 1) % 7));

your $dt should then have the value you seek

You can do this way

echo date("l M-d-Y", strtotime('monday this week'));
echo date("l M-d-Y", strtotime('sunday this week'));
echo date("l M-d-Y", strtotime('monday last week'));
echo date("l M-d-Y", strtotime('sunday last week'));
echo date("l M-d-Y", strtotime('monday next week'));
echo date("l M-d-Y", strtotime('sunday next week'));

You can also search monthwise

echo date("l M-d-Y", strtotime('first day of this month'));
echo date("l M-d-Y", strtotime('last day of this month'));
echo date("l M-d-Y", strtotime('first day of last month'));
echo date("l M-d-Y", strtotime('last day of last month'));
echo date("l M-d-Y", strtotime('first day of next month'));
echo date("l M-d-Y", strtotime('last day of next month'));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM