我需要一种方法来获取当前日期的前一个星期日到星期六的日期范围。
例如,如果今天是 8/15,我想要 8/4 - 8/10。
$to = new DateTime('2013-08-10');
$to->modify('-' . (($w = $to->format('w')) != 6 ? $w + 1 : 0) . ' day');
$from = clone $to;
$from->modify('-6 day');
echo $from->format('m/d') . "-" . $to->format('m/d'); # 08/04-08/10
$to = new DateTime('2013-08-10');
$to->modify('last Saturday');
$from = clone $to;
$from->modify('-6 day');
echo $from->format('m/d') . "-" . $to->format('m/d'); # 07/28-08/03
我个人会做这样的事情: -
$end = (new \DateTime())->modify('last saturday');
$start = (new \DateTime())->setTimestamp($end->getTimestamp())->modify('- 6 days');
$interval = new \DateInterval('P1D');
$period = new \DatePeriod($start, $interval, $end->add($interval));
foreach($period as $day)
{
$result[] = $day->format('d-m-Y');
}
var_dump($result);
输出:-
array (size=7)
0 => string '04-08-2013' (length=10)
1 => string '05-08-2013' (length=10)
2 => string '06-08-2013' (length=10)
3 => string '07-08-2013' (length=10)
4 => string '08-08-2013' (length=10)
5 => string '09-08-2013' (length=10)
6 => string '10-08-2013' (length=10)
DateTime类非常有用。
function getPreviousSundayAndSatruday($today = NULL)
{
$today = is_null($today) ? time() : $today;
// If today is Sunday, then find last week
if(date("w", $today) == 0){
$saturdayTimeStamp = strtotime("last Saturday");
$sundayTimeStamp = strtotime("last Sunday");
}
// If it is Saturday, check from last Sunday until today
else if(date("w", $today) == 6){
$saturdayTimeStamp = strtotime("this Saturday");
$sundayTimeStamp = strtotime("last Sunday");
}
// Else it's a day of the week, so last Saturday to two Sundays before.
else{
$saturdayTimeStamp = strtotime("last Saturday");
$sundayTimeStamp = strtotime("last Sunday - 1 week");
}
return array(
'saturday' => $saturdayTimeStamp,
'sunday' => $sundayTimeStamp
);
}