I am trying to perform a function that selects only the days of a certain range of dates that coincide with the condition of a period of time (for example: the first Friday of each month, the last Friday of each month, all the Friday, etc ...), I've been looking for how to do it and it seems that the php DatePeriod class is a good choice.
One of the problems that I have encountered has been that in this range of dates the $endDay
was not being included but increasing one second to the time $end->setTime(0,0,1);
I have solved this.
Now, the same does not happen with the $startDay
, in this case when I generate a period it seems to be ignoring that the start date complies with the condition of the period.
This is my code:
PHP
/* http://php.net/manual/es/datetime.formats.relative.php */
function daysByPeriod($startDay,$endDay,$inter){
$start = new DateTime($startDay);
$end = new DateTime($endDay);
// Arreglo para incluir la fecha fin al periodo
$end->setTime(0,0,1);
$interval = DateInterval::createFromDateString($inter);
$period = new DatePeriod($start, $interval, $end);
foreach ($period as $dt) {
echo $dt->format("l Y-m-d") . "<br>";
}
}
$dateStart1='20170706';
$dateEnd1='20180105';
echo "<strong>Primer viernes</strong> del mes del $dateStart1 al $dateEnd1<br>";
// Está incluyendo el día 2017-07-06 que no es viernes
// No está pintando el día 2017-07-07 que es viernes
daysByPeriod($dateStart1,$dateEnd1,'first friday of next month');
$dateStart2='20170525';
$dateEnd2='20180105';
echo "<strong>Último viernes</strong> del mes del $dateStart2 al $dateEnd2<br>";
// Está incluyendo el día 2017-05-25 que no es viernes
// No está pintando el día 2017-05-26 que es viernes
daysByPeriod($dateStart2,$dateEnd2,'last friday of next month');
$dateStart3='20170805';
$dateEnd3='20180105';
echo "Cada <strong>mes</strong> del $dateStart3 al $dateEnd3<br>";
// Aquí incluye la fecha inicio sin problema dentro el rango
daysByPeriod($dateStart3,$dateEnd3,'1 month');
$dateStart4='20170622';
$dateEnd4='20180105';
echo "Los <strong>viernes</strong> del $dateStart4 al $dateEnd4<br>";
// Está incluyendo el día 2017-06-22 que no es viernes
// Aquí incluye la fecha inicio sin problema dentro el rango
daysByPeriod($dateStart4,$dateEnd4,'next friday');
Could someone help me out with this? Thanks.