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 />";
}
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.
A date period allows iteration over a set of dates and times, recurring at regular intervals, over a given period.
In PHP, the period is the concatenation operator. Putting the periods in tells PHP to concatenate "mod/" to $modarrayout and then concatenate the resulting string to "/bar. php" .
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 />";
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With