Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to get previous Sunday of a specific date in the past..?

Tags:

I'm retrieving an entry from a database with a date associated with it.

I want to be able to get the previous Sunday and the next Saturday relative to that specific date to populate a jQuery datepicker.

I know how to do it with the actual time/date with :

strtotime('last Sunday') 

but I don't know how to do that for a date other than now...

Thanks.

like image 391
pnichols Avatar asked Sep 18 '10 17:09

pnichols


2 Answers

Use the second argument of strtotime to specify the date to calculate "last Sunday" and other relative dates from:

strtotime('last Sunday', strtotime('09/01/2010')); 

http://us2.php.net/strtotime

Example:

echo date('m/d/Y', strtotime('last Sunday', strtotime('09/01/2010'))); 

Output:

08/29/2010 
like image 60
leepowers Avatar answered Oct 04 '22 22:10

leepowers


You could also use the datetime class to do this. The code below would work:

 $date = new DateTime('09/01/2010'); $date->modify('last Sunday'); echo $date->format('d/m/Y'); 
Output: 29/08/2010 

Have a look at http://ca2.php.net/manual/en/class.datetime.php. The constructor takes two optional arguments, the first of which is a date string for the object (defaulting to now) and the second is a DateTimeZone object (defaults to the time zone set in PHP.ini). The modify method then alters the date using the same expressions that strtotime() support and the format method formats the date using the same format strings as date(). Basically this does the same as pygorex1's example but using object oriented syntax.

like image 39
Jeremy Avatar answered Oct 04 '22 21:10

Jeremy