获取每两个月一次的星期一



我试图获取每个星期一的日期,每次跳过一个月,但我只得到第一周的星期一。这是我的代码:

$begin = new DateTime("2017-04-01");
$end = new DateTime("2017-08-31");
$interval = DateInterval::createFromDateString("next monday of +2 months");
$period = new DatePeriod($begin, $interval, $end);
foreach ( $period as $dt )
            {
// echo the date for each monday found in the second month
}

任何帮助将不胜感激。

您似乎混合了$begin$end值。此外,DateInterval每个月只有一个星期一。我无法找到每隔一个月的每个星期一获取的间隔表达式,所以我手动进行了过滤。在此示例中,我们使用从开始日期开始的月份,并包括从该日期开始的星期一,跳过两个月,依此类推。

<?php
$end = new DateTime("2017-04-01");
$begin = new DateTime("2007-08-31");
$month_even = ((int) $begin->format('m')) % 2 === 0;
$interval = DateInterval::createFromDateString("next monday");
$period = new DatePeriod($begin, $interval, $end);
foreach ($period as $dt) {
    // Check if we want to show even months, make sure that the current month is even
    // or, if we want to show odd months, the month should be odd.
    if ((((int) $dt->format('m')) % 2 === 0) === $month_even) {
        echo $dt->format('d-m-Y') . PHP_EOL;
    }
}

输出:

31-08-2007
01-10-2007
[...]
06-02-2017
13-02-2017
20-02-2017
27-02-2017

最新更新