如何在PHP中获得当天的前一个星期日和星期六

时间:2013-08-15 14:07:44

标签: php date time

我需要一种方法来获取当前日期的前一个星期日到星期六的日期范围。

例如,如果今天是8/15,我希望8/4 - 8/10。

3 个答案:

答案 0 :(得分:0)

1。现在的日期是8/10。代码,如果日期范围必须是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

2。现在的日期是8/10。代码,如果日期范围必须是7 / 28-8 / 03:

$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

答案 1 :(得分:0)

我个人会这样做: -

$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类非常有用。

答案 2 :(得分:-4)

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