Base de conhecimentoCentro de Exames
PT · PTPortuguês (Portugal)
Escolher idioma13

CKTIS / PHP

DatePeriod

Percorre datas recorrentes sem construir a lista.

Versão: PHP 8.4; repository runtime, production runtime not attested

Sintaxe

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

Percorre datas recorrentes sem construir a lista. Por predefinição inclui o início e omite a data final. EXCLUDE_START_DATE exclui o início e INCLUDE_END_DATE inclui o fim atingido exatamente. Com número de recorrências o início incluído soma uma ocorrência.

$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"]]

Exemplos

<?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))]);

Resultado

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

Fontes