Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php - find date for same day of week for last year

Tags:

date

php

So, in PHP i'm trying to return a date value for last year based on the same day of week. EX: (Monday) 2011-12-19 inputted should return (Monday) 2010-12-20.

I was just doing it simply by -364 but then that was failing on 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, that is failing when you try to input a Sunday date, as it does a 0 (sunday) minus 6 (saturday of last year date), and returns with a value T-6. IE inputting 2011-12-25 gets you 2010-12-19 instead of 2011-12-26.

I'm kind of stumped to find a good solution in php that will work for leap years and obviously all days of the week.

Any suggestions?

Thanks!

like image 587
alpharoot Avatar asked Dec 19 '11 22:12

alpharoot


2 Answers

How about this, using PHP's DateTime functionality:

$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
like image 78
lonesomeday Avatar answered Sep 16 '22 13:09

lonesomeday


$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);

That gives:

This date: 2011-12-19 Monday 1 51
Old date : 2010-12-20 Monday 1 51
like image 41
hakre Avatar answered Sep 18 '22 13:09

hakre