kimondoe
kimondoe

Reputation: 619

iterate and print all date in range in twig

I am trying to iterate all dates in twig

I have tried using this:

{% for x in range(startDate|date('U'), endDate|date('U'), 86400 ) %}
  {{ x|date('m/d') }}
{% endfor %} 

It worked in some dates. but if my startDate is 10/01/2015 and endDate is 10/31/2015 10/25 is displayed twice.

the scenario can be replicated on octobers of any year on 4th sundays

I don't know if it's only me that can replicate this.

Is there any other way to iterate all dates in range in twig?

Upvotes: 3

Views: 1422

Answers (1)

Maerlyn
Maerlyn

Reputation: 34105

The \DatePeriod class was created for exactly this purpose, and it's available since php5.3.

$start = DateTime::createFromFormat("Y-m-d", "2015-10-01");
$end = DateTime::createFromFormat("Y-m-d", "2015-11-01");
$interval = new DateInterval("P1D");

$range = new DatePeriod($start, $interval, $end);

foreach ($range as $date) {
    var_dump($date->format("Y-m-d"));
}

You can try it at: https://3v4l.org/vFsb6

Upvotes: 1

Related Questions