soenguy soenguy - 3 years ago 796
Twig Question

Twig date loop each day in a period

So, here's my situation, I have a beginning date and an ending date, with Twig I want to be able to loop through all days in the so called period so that I could print out every day. Of course, that's just for understanding how to do it, the goal is to get them into a chart. Anyway, I have the following code (with what are my vars) :

{% set start_year = date(start) | date('d-m-Y') %}
{% set end_year = date(end)| date('d-m-Y') %}

{% for i in start_year..end_year %}
{{ i }}
{% endfor %}

var is
and my
var is
. The values don't matter as they could change, but that's the format I have.

This actually prints out
0 1
which I don't understand at all. If anyone has an idea either how to do this or how to fix what I'm doing, it would be really nice. Thanks.

Answer Source

You cannot define a range of exact dates (neither as range in php) but you can create a range of seconds with step of a 24 hours second which is 86400; if you use date('U') it will convert date string to seconds since the Unix Epoch (same as Time() in php)

{% set start_date = '01-06-2014' %}
{% set end_date = '05-06-2014' %}
{% for x in range(start_date|date('U'), end_date|date('U'), 86400 ) %}
   {{ x|date('d/m/Y') }}<br>
{% endfor %}

Pay attention the format of date to use - as separator not / because it will lead to totally different result

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download