I experienced that there is a difference between real DateTime objects (as now
is one) and strings composed to "fake DateTime objects" (ie. {% set myDate = '2014/06/24' %}
).
Sometimes it makes no difference and you can use one or the other. The date()
filter for example works fine with both. But this isn't always the case, the localeTime()
method is an example that exclusively takes real DateTime objects.
Applying a date
or date_modify
filter to the myDate
(string) variable is apparently not sufficient to convert it. The only solution I found is to modify now
or fetch a DateTime object from an entry field, but I am looking for a way to generate one solely with twig in the template.
.
Edit:
Thanks for your answers so far, but I still don't get this to work. For me it always results in the following template error when I use a DateTime method on a manually composed DateTime object:
Method "localeTime" for object "DateTime" does not exist
Here my example code for easy reproducibility. I more and more believe this is rather a problem with those DateTime methods and not with the way I compose the object.
{# Set var to string in supported format #}
{% set myDatetimeString = '2014-06-24 23:40' %}
{# Use date() function to convert string to DateTime object #}
{% set myDatetimeObject = date(myDatetimeString) %}
{# Alternatively use date_modify filter to convert string to DateTime object #}
{% set myDatetimeObject = myDatetimeString|date_modify('+0 day') %}
{# DateTime method doesnt work with these "objects" !! #}
{{ myDatetimeObject.localeTime() }}
{# But DateTime methods work with the `now` DateTime object #}
{{ now.localeTime() }}
{{ now.day() }}
{{ now.iso8601() }}