Php - find the date on the same day of the week for the last year

So, in PHP, I am trying to return the date value for the last year depending on the same day of the week. EX: (Monday) 2011-12-19 entered should return (Monday) 2010-12-20.

I just did it just at -364, but then it was unsuccessful in leap years. I came across another function:

$newDate = $_POST['date'];
$newDate = strtotime($newDate);
$oldDate = strtotime('-1 year',$newDate);

$newDayOfWeek = date('w',$oldDate);
$oldDayOfWeek = date('w',$newDate);
$dayDiff = $oldDayOfWeek-$newDayOfWeek;

$oldDate = strtotime("$dayDiff days",$oldDate);

echo 'LAST YEAR DAY OF WEEK DATE = ' . date('Ymd', $oldDate);

however, this does not work when you try to enter a Sunday date, since it executes 0 (Sunday) minus 6 (Saturday by last year's date) and returns with a value of T-6. Input IE 2011-12-25 gets you 2010-12-19 instead of 2011-12-26.

I am a little shy to find a good solution in php that will work for leap years and obviously all days of the week.

Any suggestions?

Thank!

+5
4

, PHP DateTime:

$date = new DateTime('2011-12-25');  // make a new DateTime instance with the starting date

$day = $date->format('l');           // get the name of the day we want

$date->sub(new DateInterval('P1Y')); // go back a year
$date->modify('next ' . $day);       // from this point, go to the next $day
echo $date->format('Ymd'), "\n";     // ouput the date
+8
$newDate = '2011-12-19';

date_default_timezone_set('UTC');
$newDate = strtotime($newDate);
$oldDate = strtotime('last year', $newDate);
$oldDate = strtotime(date('l', $newDate), $oldDate);

$dateFormat = 'Y-m-d l w W';

echo "This date: ", date($dateFormat, $newDate), "\n"; 
echo "Old date : ", date($dateFormat, $oldDate);

:

This date: 2011-12-19 Monday 1 51
Old date : 2010-12-20 Monday 1 51
+4

Use strtotime () to get the date for the same week last year.

Use the format {$ year} -W {$ week} - {$ weekday}, for example:

echo date("Y-m-d", strtotime("2010-W12-1"));

And you can do this as long as possible:

<?php

  for($i = 2011; $i > 2000; $i--)
    echo date("Y-m-d", strtotime($i."-W12-1"));

?>
+2
source

Make it easier :)

echo date('Y-m-d (l, W)').<br/>;
echo date('Y-m-d (l, W)', strtotime("-52 week"));

Edit: I forgot to write a conclusion: :)

2015-05-06 (Wednesday, 19)
2014-05-07 (Wednesday, 19)
+2
source

All Articles