Twig date loop each day in a period - twig

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.

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

{% 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.

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

Related

How to calculate the composite's elements and get total of them?

Hi I have a composite that has a QTY field and a TOTAL PRICE field and the table below would calculate and display the subtotal. It works properly when there is only one row of composite, but when I add more items, the subtotal field displays two subtotals instead of one as a whole. I want the subtotal field to display 24 instead of 4 and 20. How can twig solve this implementation? In my SUBTOTAL, I have
{% for item in data.item %}
{% set total_qty = (item.qty)|number_format(2,'.',',') %}
{% set per_price = (item.total)|number_format(2,'.',',') %}
{% set net_cost = (total_qty * per_price )|number_format(2,'.',',') %}
{{ net_cost }}
{% endfor %}
Here is the screenshot to give you better understanding
Don't output the net cost inside the for loop.
First create the sum, then display it after the loop.
Also don't use number_format before the final result.
{% set net_cost = 0 %}
{% for item in data.items %}
{% set net_cost = nest_cost + item.qty * item.total %}
{% endfor %}
{{ net_cost|number_format(2, '.', ',') }}
demo

How to add n-days to twig date format within a for-loop?

I'm working with twig and got the date and format working. I have a start date (let's say todays day) and I'd like to print every day into a table cell.
I have my date field in the var datum and I'm able to add 1 day with this. it's working.
{% set datum = date(current_user.cwmon)|date_modify("+1 day")|date('D d.m.y') %}
when I put this into a for loop, I get not the answer I'd like to.
the code itself:
{% for j in 0..6 %}
{% set datum = date(current_user.cwmon)|date_modify("+1 day")|date('D d.m.y') %}
// other code
{{ j }}: {{ datum }}
// other code
{% endfor %}
is there a way to use my var j instead of +1 day?
Whatever I try I get an error.
my desired result:
0: Mon 15.01.19
1: Tue 16.01.19
...
6: Sun 20.01.19
Thank you very much in advance.
apparently the answer is quite simple.
{% for j in 0..6 %}
{% set datum = YOUR_DATE|date_modify("+" ~ j ~ " day")|date('D d.m.y') %}
{% endfor %}
with this, datum has the correct value and adds j to itself.
Another solution is overwriting the datum variable
{% set datum = current_user.cwmon %}
{% for j in 0..6 %}
{% set datum = date(datum)|date_modify("+1 day")|date('D d.m.y') %}
// other code
{{ j }}: {{ datum }}
// other code
{% endfor %}
demo

Symfony2. Twig: Doesn't work logic function when date variable changes

{% set event_date = event.schedule|date('d-m-y') %}
{% set nowdate = "now"|date('d-m-y') %}
{% if event_date < nowdate %}
view some 1
{% else %}
view some 2
{% endif %}
If change event_date bigger or lower than nowdate, have one result: view some 2.
Why doesn't work?
You are in a string comparison situation. For better approach this, use the U filter as follow:
{% set event_date = event.schedule|date('U') %}
{% set nowdate = "now"|date('U') %}
{% if event_date < nowdate %}
view some 1
{% else %}
view some 2
{% endif %}
{{ event_date }}
Live testing in this fiddle.
Hope this help
You're comparing strings. d-m-y is not a usable format for comparing dates. Try Y-m-d, where the parts are in order of importance.
Even better, you could compare two \DateTime objects instead of strings. I assume event.schedule is one, you just need to pass one for the current date to twig.
In addition to the date filter, Twig defines a date() function which has been designed precisely to compare dates.

how to subtract dates in twig?

{%for mat in setQuery %}
{% set datePost = mat.data_criacao|date('d-m-Y') %}
{% set today = "now"|date('d-m-Y') %}
{{today- datePost}}
{% endfor %}
datePost = 17-04-2015
today = 06-05-2015
the example above returns it: -11
The issue was resolved with the following code:
{% set datePost = mat.data_criacao|date('d-m-Y') %}
{% set today = "now"|date('d-m-Y') %}
{% set difference = date(today).diff(date(datePost))%}
{% set leftDays = difference.days %}
{% if datePost == today %}
1 day
{% else %}
{{ leftDays }}
{% endif %}
You must write your custom twig extension:
You must write a twig function as described here with the following code for make diff via php function:
$calcFrom = $from;
$calcTo = $to;
$now->diff($calcFrom)->format("%a")
And make it available via a Twig extension.
If you are using symfony2 framework You can use the KnpTimeBundle
In the Twig:
This compare with the current date:
{# Returns something like "3 minutes ago" #}
{{ time_diff(form) }}
This compare with the another date:
{# Returns something like "3 minutes ago" #}
{{ time_diff(form , to ) }}
Hope this help

Counting the number of elements in array

I am looking to count the number of entries I have in an array in Twig. This is the code I've tried:
{%for nc in notcount%}
{{ nc|length }}
{%endfor%}
This however only produces the length of the string of one of the values in the array.
{{nc}} will produce an output of all the values of the array (there are 2) but I want the output to be just the number 2 (the count) and not all the information in the array.
Just use the length filter on the whole array. It works on more than just strings:
{{ notcount|length }}
This expands on the answer by Denis Bubnov.
I used this to find child values of array elements—namely if there was a anchor field in paragraphs on a Drupal 8 site to build a table of contents.
{% set count = 0 %}
{% for anchor in items %}
{% if anchor.content['#paragraph'].field_anchor_link.0.value %}
{% set count = count + 1 %}
{% endif %}
{% endfor %}
{% if count > 0 %}
--- build the toc here --
{% endif %}
Best practice of getting length is use length filter returns the number of items of a sequence or mapping, or the length of a string. For example: {{ notcount | length }}
But you can calculate count of elements in for loop. For example:
{% set count = 0 %}
{% for nc in notcount %}
{% set count = count + 1 %}
{% endfor %}
{{ count }}
This solution helps if you want to calculate count of elements by condition, for example you have a property name inside object and you want to calculate count of objects with not empty names:
{% set countNotEmpty = 0 %}
{% for nc in notcount if nc.name %}
{% set countNotEmpty = countNotEmpty + 1 %}
{% endfor %}
{{ countNotEmpty }}
Useful links:
length
set
for
{%for nc in notcount%}
{{ loop.index }}
{%endfor%}
loop.index -- The current iteration of the loop.
for reference:https://twig.symfony.com/doc/2.x/tags/for.html

Resources