PHP:在X天内每两周更新一次DateInterval

时间:2017-05-24 01:22:19

标签: php arrays date date-range dateinterval

我有开始日期和结束日期 我试图获得每两周一次的周二和周三。

示例:

  

2017-05-23(tu)
  2017-05-24(我们)

     

2017-06-06(tu)
  2017-06-07(我们)
  ...

我在PHP中尝试做的事情:

$start = new FrozenTime('2017-05-23'); // Date is in this format 'cause I'll save into DB  
$endOfYear = $start->endOfYear();  

$perWeek = new \DateInterval('P14D'); // I want every 2 weeks

$periodPerWeek = new \DatePeriod($start, $perWeek, $endOfYear);  

$days = ['2', '3']; // Tuesday and Wednesday  

foreach ($periodPerWeek as $value) {
   if (in_array($value->format('N'), $days)) {
        $test[] = [
            'start' => $value
        ];    
   }
}  

结果:

"start": "2017-05-23",  
"start": "2017-06-06",  
"start": "2017-06-20",  

它只在阵列中获得一个日期。我也需要得到周三的消息!我该怎么做?

重要:
开始日期不会总是星期二。用户可以选择他想要的工作日。

实施例 用户可以每两周选择一次SU,WE和FR。

// start date example: 2017-05-20 (saturday)
// output should be like:
2017-05-22 (SU)  
2017-05-24 (WE)  
2017-05-26 (FR)  
2017-06-05 (SU)  
2017-06-07 (WE)  
2017-06-09 (FR)  
...

2 个答案:

答案 0 :(得分:0)

你非常接近,但DatePeriod只会产生相隔14天的日期,而不是每天。

根据您的问题,如果您的开始日期始终是星期二,您只需要在每个迭代循环中获取当前日期,然后是下一个日期。

请参阅以下内容:

// Prepare start and end dates. Assume start date is a Tuesday based on OP's question
$start = new DateTime('2017-05-23');
$end = new DateTime('2017-12-31');

// Prepare interval and date period
$interval = new DateInterval('P14D');
$period = new DatePeriod($start, $interval, $end);

// Prepare dates collection
$dates = [];

// Iterate over date period
foreach ($period as $date) {
    // Prepare dates
    $tuesday = clone $date;
    $wednesday = $date->add(new DateInterval('P1D'));

    // Append dates to collection
    array_push($dates, $tuesday, $wednesday);
}

var_dump($dates);

答案 1 :(得分:0)

一种方法

/**
 * @param \DateTime $start 
 * @param \DateTime $end 
 * @param array $days i.e. ['tue', 'wed', 'sat']
 * 
 * @return array
 */

function every_two_weeks($start, $end, $days) 
{
    $dates = [];

    $mon = new DateTime('mon this week '.$start->format('Y-m-d'));

    while ($mon <= $end) {
        $of = 'this week '.$mon->format('Y-m-d');

        foreach ($days as $day) {
            $date = new DateTime("$day $of");

            if ($date < $start) {
                continue;
            }

            if ($date > $end) {
                break 2;
            }

            $dates[] = $date;
        }

        $mon->add(new DateInterval('P2W'));
    } 

    return $dates;
}

用法:

$start = new DateTime('2017-05-23');
$end = new DateTime('2017-06-21');

$dates = every_two_weeks($start, $end, ['tue', 'wed', 'sat']);

输出:

2017-05-23 Tue
2017-05-24 Wed
2017-05-27 Sat
2017-06-06 Tue
2017-06-07 Wed
2017-06-10 Sat
2017-06-20 Tue
2017-06-21 Wed

3v4l演示