2

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?

B.1988
  • 35
  • 2
  • 7

4 Answers4

1

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'));
Jazzzzzz
  • 1,593
  • 15
  • 16
0

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, Y H:i:s will output November 28, 2016 06:18:03.

Karol Gasienica
  • 2,825
  • 24
  • 36
0
$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));
Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
  • For my case, this answer is the best one. I only substituted the output date format to 'd/m/Y'. Thank you everyone for very prompt responses! – B.1988 Nov 29 '16 at 11:21
0

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

Talus
  • 754
  • 7
  • 18