8

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 %}

My start var is 01-01-2003 and my end var is 10-05-2014. 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.

soenguy
  • 1,332
  • 3
  • 11
  • 23
  • Can you pass the number of days between `start_year` and `end_year` into `Twig`? If so, use `date_modify` filter – Bartek Jun 06 '14 at 14:40

3 Answers3

24

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 %}

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

Javad
  • 4,339
  • 3
  • 21
  • 36
  • 1
    It doesn't work all the time. Currenlty, I have some issue with hour change in canada (+1 in autumn, -1 in spring) – Matrix818181 Oct 31 '16 at 18:48
0
{% set pd_begdate = header_data.pd_begdate %}
{% set pd_enddate = header_data.pd_enddate ~ ' 23:59:59' %}
{% for key, count_item in range(pd_begdate|date('z'), pd_enddate|date('z'), 1)|slice(column_offset, column_count, 'preserve_keys') %}
    {% set item = pd_begdate|date_modify('+'~ key ~' day') %}
    <td class="tr5 td9"><p class="p9 ft0">{{ item|date("M") }}<br>{{ item|date("d") }}<br>{{ item|date("D") }}<br>{{ key + 1 }}</p></td>
{% endfor %}

This solution works for day light savings.

Pang
  • 9,564
  • 146
  • 81
  • 122
xfloys2112
  • 605
  • 1
  • 5
  • 13
0

I had trouble with the solution when I tried to iterate over an entire year - after about 8 months, I found it would drop a day.

But based on the solution How to add n-days to twig date format within a for-loop?, I found that this would work:

{% set yearstart = "01-01-2003"|date('m-d-Y') %}
{% set eachday = "" %}
{% for i in range(0,365) %}
    {% set eachday = yearstart|date_modify("+" ~ i ~ "day")|date('m-d-y') %}
{% endfor %}