开发者

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

I'm retrieving开发者_JS百科 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.


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


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.


You can use week day offset. In PHP for arbitrary date:

<?php

define('SEC_IN_DAY', (24*60*60));

$d = strtotime('2013-04-15');
// "w" is the day of the week. 0 for Sunday through 6 for Saturday
$delta_sun = -date('w', $d);
$delta_sat = $delta_sun + 6;

echo 'The day ' . date('Y-m-d H:i:s', $d) . "\n";
echo 'Last Sunday '. date('Y-m-d H:i:s', $d + $delta_sun * SEC_IN_DAY) . "\n";
echo 'Next Saturday '. date('Y-m-d H:i:s', $d + $delta_sat * SEC_IN_DAY) . "\n";

The same in MySQL:

SET @d := '2013-04-15';
SET @delta_sun := -DATE_FORMAT(@d, '%w');
SET @delta_sat := @delta_sun + 6;

SELECT 'The day' AS `name`, DATE(@d) AS `date`
  UNION ALL
SELECT 'Last Sunday' AS `name`, DATE_ADD(@d, INTERVAL @delta_sun DAY) AS `date`
  UNION ALL
SELECT 'Next Saturday' AS `name`, DATE_ADD(@d, INTERVAL @delta_sat DAY) AS `date`
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜