如何在DatePeriod中包括结束日期? [英] How to include the end date in a DatePeriod?

查看:151
本文介绍了如何在DatePeriod中包括结束日期?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取本周所有工作日的日期范围.我已经编写了以下代码.

I am trying to get a Date range for all workdays this week. I have written the following code to do so.

$begin = new DateTime('monday this week'); 2016-07-04
$end = clone $begin;
$end->modify('next friday'); // 2016-07-08

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval, $end);



foreach($daterange as $date) {
    echo $date->format('Y-m-d')."<br />";
}

输出

  • 2016-07-04
  • 2016-07-05
  • 2016-07-06
  • 2016-07-07
  • Output

    • 2016-07-04
    • 2016-07-05
    • 2016-07-06
    • 2016-07-07
    • 在输出星期五中缺少.我可以通过执行$end->modify('next saturday')来解决此问题,但我想知道为什么DatePeriod的最后一天不包含在范围内.

      In the output friday is missing. I can fix this by doing $end->modify('next saturday') but I was wondering why the last day of a DatePeriod is not included in the range.

      推荐答案

      迭代器似乎检查时间和日期,如果endDate中的时间小于或等于ind中的时间,则它排除end元素.开始日期.

      The iterator seems to check the time as well as the date, it excludes the end element if the time in the endDate is less that or equal to the time in the start date.

      因此,请确保结束日期的时间至少比开始日期的时间长一秒.

      So ensure the time of the end date is at least a second greater that that of the start date.

      // this will default to a time of 00:00:00
      $begin = new DateTime('monday this week'); //2016-07-04
      
      $end = clone $begin;
      
      // this will default to a time of 00:00:00    
      $end->modify('next friday'); // 2016-07-08
      
      $end->setTime(0,0,1);     // new line
      
      $interval = new DateInterval('P1D');
      $daterange = new DatePeriod($begin, $interval, $end);
      
      foreach($daterange as $date) {
          echo $date->format('Y-m-d')."<br />";
      }
      

      这篇关于如何在DatePeriod中包括结束日期?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆