Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Twig date loop each day in a period

Tags:

twig

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

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.

like image 672
soenguy Avatar asked Jun 06 '14 09:06

soenguy


1 Answers

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

like image 122
Javad Avatar answered Sep 21 '22 11:09

Javad