Peter
Peter

Reputation: 9123

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

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.

Upvotes: 32

Views: 31410

Answers (3)

panda098
panda098

Reputation: 93

In PHP 8.2 you can use DatePeriod::INCLUDE_END_DATE as constructor option!

https://www.php.net/manual/en/class.dateperiod.php#dateperiod.constants.include-end-date

Upvotes: 9

newage
newage

Reputation: 909

Try this code

<?php
$begin = new DateTime('2016-07-04');
$end = clone $begin;
$end->modify('next friday'); // 2016-07-08
$end->modify('+1 day');

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

foreach ($daterange as $date) {
    echo $date->format('Y-m-d') . PHP_EOL;
}

Upvotes: 18

RiggsFolly
RiggsFolly

Reputation: 94662

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

Upvotes: 60

Related Questions