1

Using Symfony 2.3.4 and Twig. I'm trying to show an objects attribute which is, and I quote, "an Object of Class DateTime" and I need something to convert it to a string(I'm guessing a filter).

{{ r.birthday }}

Any tips appreciated.

jmiguel
  • 296
  • 2
  • 5
  • 15
  • possible duplicate of [How to render a DateTime object in a Twig template](http://stackoverflow.com/questions/8318914/how-to-render-a-datetime-object-in-a-twig-template) – Nic Wortel May 07 '14 at 06:33

3 Answers3

3

From the documentation http://twig.sensiolabs.org/doc/filters/date.html

{{ r.birthday|date("m/d/Y") }}
fejese
  • 4,601
  • 4
  • 29
  • 36
3

You can either use the date filter if you want to display the date in a static format (for instance, if you allways want to display something like 2014-05-07, regardless of the locale of the user), or you can use the localizeddate filter to display a date that is localized for the user's language and location.

For instance, if you always need the same format:

{{ r.birthday|date('Y-m-d\\TH:i:sP') }}

will always return a date/time in the following format:

2014-05-07T08:39:11Z

which is useful for machine-readable date strings, for instance in an Atom feed.

However, if you want to display date/times for humans, I'd recommend using the localizeddate filter:

{{ r.birthday|localizeddate('long', 'short') }}

will return something like:

February 6, 2014 at 10:52 AM (using English locale)
6 februari 2014 10:52 (using Dutch locale)
6 février 2014 10:52 (using French locale)
6. Februar 2014 10:52 (using German locale)

See my answer on 'How to render a DateTime object in a Twig template' for more information.

Community
  • 1
  • 1
Nic Wortel
  • 11,155
  • 6
  • 60
  • 79
0

If the r.brithdaty is instance of DateTime object you can easily use the format command to return the string format:

{{ r.birthday.format('m/d/Y') }}

Follow this link for more info DateTime Format

Javad
  • 4,339
  • 3
  • 21
  • 36