1

I'm trying to build a chart to show student progress, showing only the last handful of weeks (mondays) as m/d. Here is what I've tried:

$here = date( 'W', strtotime('this Monday'));
$then = date('W', strtotime('-70 days', strtotime('this Monday')));
    for($i = $then; $i<=$here; $i++)
    {
        $temp = date('W', strtotime($i));
        $tempa = strtotime($temp);
        $newd = date('m/d', $tempa);
        list .=",".$newd);
    }

this current iteration gives me a series of 01/01. Can someone help? Thanks.

sukebe7
  • 89
  • 6

2 Answers2

4

You can use PHP's DateTime class.

<?php 
$nextMonday = new \DateTime(date('Y-m-d') . ' previous Monday');
echo "<br/>" . $nextMonday->format('Y-m-d');
for ($i=1 ; $i<=9 ; ++$i) {
 $nextMonday->sub(new DateInterval('P7D'));
 echo "<br/>" . $nextMonday->format('Y-m-d');
}

Output:

2019-04-22
2019-04-15
2019-04-08
2019-04-01
2019-03-25
2019-03-18
2019-03-11
2019-03-04
2019-02-25
2019-02-18

See it live here

Code Explained:

  • First get previous Monday.

  • Now, add loop for 1 to 9 (We already have recent Monday).

  • In the loop, subtract date by 7 days (P -> Period, 7D -> 7 Days)

  • By this, we can step over to only Mondays and (Monday to Monday) is 7 days difference.

  • It will print last 10 Mondays (1 before and 9 after the loop).

Pupil
  • 23,834
  • 6
  • 44
  • 66
  • 1
    Fabulous. I tried other similar questions, but I couldn't get them to work quite right. Yours is customizable, so that others will be able to adopt it. – sukebe7 Apr 24 '19 at 10:24
  • 1
    oops, ....er....how do I reverse this order? It actually will be one big string, like "02-18,02-25,03-04,03-11,03-18,03-25" ..etc. – sukebe7 Apr 24 '19 at 12:07
  • Replace `$nextMonday->sub(new DateInterval('P7D'));` by `$nextMonday->add(new DateInterval('P7D'));` – Pupil Apr 24 '19 at 12:08
0
$thisMonday = strtotime('this Monday');
$lastMonday = $thisMonday - 86400 * 7; //a day has 86400 seconds
$secondLastMonday = $thisMonday - 86400 * 14;

..... and so on!

Kapsonfire
  • 1,013
  • 5
  • 17