如何在两个日期之间的第二个星期日每个月?

时间:2016-09-24 08:33:26

标签: php

我有两个约会,我希望每个月在第二个星期日两个提到日期之间。如何在PHP代码中执行此操作?

在我提到的两个日期之下。

$start_date = '2016-08-24';
$end_date = '2017-09-24';

谢谢

3 个答案:

答案 0 :(得分:2)

您可以使用可以与relative formats一起使用的DateTime class,如下所示:

$start_date = new DateTime('2016-08-24');
$end_date = new DateTime('2017-09-24');

$dt = clone $start_date;
$dt->modify('first day of this month')->modify('+2 Sundays');
while ($dt <= $end_date) {
    if ($dt >= $start_date) $result[] = $dt->format('Y-m-d');
    $dt->modify('first day of next month')->modify('+2 Sundays');
}
print_r ($result);

输出结果为:

Array
(
    [0] => 2016-09-11
    [1] => 2016-10-09
    [2] => 2016-11-13
    [3] => 2016-12-11
    [4] => 2017-01-08
    [5] => 2017-02-12
    [6] => 2017-03-12
    [7] => 2017-04-09
    [8] => 2017-05-14
    [9] => 2017-06-11
    [10] => 2017-07-09
    [11] => 2017-08-13
    [12] => 2017-09-10
)

答案 1 :(得分:0)

请使用php类DateTime和DateInterval。在DateInterval手册页上,有类似于您的问题的代码示例。

答案 2 :(得分:0)

试试这个

    $startdate = '2016-08-24';
   $enddate = '2017-09-24';
    getSundays($startdate,$enddate);
    function getSundays($startdate,$enddate) {
        $startweek=date("W",strtotime($startdate));
        $endweek=date("W",strtotime($enddate));
        $year=date("Y",strtotime($startdate));
        for($i=$startweek;$i<=$endweek;$i++) {
            $result=getWeek($i,$year);
            if($result>$startdate&&$result<$enddate) {
                echo date('Y-m-d', strtotime('second sunday of '.date("F",strtotime($startdate)).' '.$year)).'<br/>';
                //echo " Sunday:"."<br>";
            }
        }
    }
    function getWeek($week, $year) {
      $dto = new DateTime();
      $result = $dto->setISODate($year, $week, 0)->format('Y-m-d');
      return $result;
    }