Is it possible to compose a DateTime object from a string? 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() }}
In Twig, the date_modify filter returns a DateTime object. Also, date is not just a filter, but also a function. The date function accepts any a DateTime object or a string in a supported format, and returns a DateTime object. Example:

{{ date("+2 years") }}


This should give you a DateTime object set for 2 years from when it's triggered.

Why is localeTime missing?

The now variable is not a regular DateTime object from PHP. It's actually an extended class ( \Craft\DateTime ). So it won't have all the convenience functions you get from now or a date field from an entry. Instead you would need to do it manually (I'm not sure if you can overwrite a function or filter in Twig). Fortunately, the locale's format string is available as a variable.

{% set myDatetimeString = '2014-06-24 23:40' %}
{% set format = craft.i18n.getTimepickerJsFormat() %}
{{ myDatetimeString|date(format) }}


You can even shorten it like this:

{% set myDatetimeString = '2014-06-24 23:40' %}
{{ myDatetimeString|date(craft.i18n.getTimepickerJsFormat()) }}


To replicate localeDate, use this:

{% set myDatetimeString = '2014-06-24 23:40' %}
{{ myDatetimeString|date(craft.i18n.getDatepickerJsFormat()) }}