views:

61

answers:

2

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.

+5  A: 

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
pygorex1
Works great.! Thanks.
pnichols
A: 

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.

Jeremy
Note that this requires PHP 5.3.
alexn
@alexn That's not true. The datetime class is available from PHP 5.2 onwards. There are some extra methods available in PHP 5.3 (add and sub come to mind) but all of the methods I used in my example are available in PHP 5.2.x.
Jeremy
Interesting... I really have to start looking into OO. I know it's a must to stay up-to-date, but OO seems to be too much/unnecessary for the type/size of project I have...
pnichols