Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

DatePeriod

Iterate recurring dates without building the whole list.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

new DatePeriod($start, $interval, $end, $options)

Iterate recurring dates without building the whole list. With an end date the start is included and the end excluded by default. EXCLUDE_START_DATE skips the first value and INCLUDE_END_DATE includes the end if reached exactly. With a recurrence count, an included start contributes an additional occurrence.

$start=new DateTimeImmutable("2024-05-01",new DateTimeZone("UTC")); $end=$start->modify("+2 days"); $step=new DateInterval("P1D");
$days=function(DatePeriod $p): array { $out=[]; foreach($p as $d){$out[]=$d->format("d");} return $out; };
echo json_encode([$days(new DatePeriod($start,$step,$end)),$days(new DatePeriod($start,$step,$end,DatePeriod::EXCLUDE_START_DATE|DatePeriod::INCLUDE_END_DATE))]);
[["01","02"],["02","03"]]

Examples

<?php
$start=new DateTimeImmutable("2024-05-01",new DateTimeZone("UTC")); $end=$start->modify("+2 days"); $step=new DateInterval("P1D");
$days=function(DatePeriod $p): array { $out=[]; foreach($p as $d){$out[]=$d->format("d");} return $out; };
echo json_encode([$days(new DatePeriod($start,$step,$end)),$days(new DatePeriod($start,$step,$end,DatePeriod::EXCLUDE_START_DATE|DatePeriod::INCLUDE_END_DATE))]);

Result

[["01","02"],["02","03"]]

Sources