Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
673 views
in Technique[技术] by (71.8m points)

php - How to include the end date in a DatePeriod?

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

Code

$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 />";
}

Output

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 />";
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...