240

One of my fields in one of my entities is a "datetime" variable.

How can I convert this field into a string to render in a browser?

Here is a code snippet:

{% for game in games %}
    ...
        <td> {{game.gameTeamIdOne.teamName}} </td>
        <td> {{game.gameTeamIdTwo.teamName}} </td>
        <td> {{game.gameDate}}</td>
    </tr>
{% endfor %}

Here is the variable in my entity class:

/**
 * @var date $gameDate
 *
 * @ORM\Column(name="GAME_DATE", type="datetime", nullable=true)
 */
private $gameDate;

And here is the error message I am getting:

An exception has been thrown during the rendering of a template ("Catchable Fatal Error: Object of class DateTime could not be converted to string in ...\app\cache\dev\twig\9b\ad\58fd3bb1517632badf1fdc7fa4a8.php line 33") in "BeerBundle:Games:gameTable.html.twig" at line 10.

gvlasov
  • 18,638
  • 21
  • 74
  • 110
Chris Ridmann
  • 2,836
  • 4
  • 18
  • 19

11 Answers11

330

Although you can use the

{{ game.gameDate|date('Y-m-d') }}

approach, keep in mind that this version does not honor the user locale, which should not be a problem with a site used by only users of one nationality. International users should display the game date totally different, like extending the \DateTime class, and adding a __toString() method to it that checks the locale and acts accordingly.

Edit:

As pointed out by @Nic in a comment, if you use the Intl extension of Twig, you will have a localizeddate filter available, which shows the date in the user’s locale. This way you can drop my previous idea of extending \DateTime.

GergelyPolonkai
  • 6,230
  • 6
  • 35
  • 69
  • 55
    `{{ game.gameDate|date('Y-m-d H:i:s') }}` for date and time. I had problems finding character for minutes. – murko Jan 12 '13 at 23:30
  • 6
    Twig's date function uses the same format as the php function (from the Twig docs). For anyone looking for other formats, http://www.php.net/manual/en/function.date.php. – JonnyS Mar 19 '14 at 20:22
  • 9
    Watch out for null values; in a similar use case, I'm seeing today's date when piping a null value to Twig's `date` function. Based on your example, you'll need to wrap it in `{% if game.gameDate is not empty %} ... {%endif}` – fazy Aug 28 '14 at 14:54
  • 4
    As for the localization, you shouldn't be extending the `DateTime` class! Instead, [simply use the `localizeddate` filter for Twig](http://stackoverflow.com/a/23424315/1001110). – Nic Wortel Oct 16 '14 at 08:47
  • Note that you have to be sure your date is correct, otherwise it will throw an exception. – COil Jun 11 '15 at 15:42
  • 1
    `{% if game.gameDate %} {{ game.gameDate|date('Y-m-d H:i:s') }} {% endif %}` would be suggested – some_groceries Jan 05 '16 at 08:52
92

You can use date filter:

{{ game.gameDate|date("m/d/Y") }}
Ondrej Slinták
  • 31,386
  • 20
  • 94
  • 126
  • 3
    Totally agree with you. It's something that should be there by default. – tftd Aug 25 '12 at 21:55
  • 2
    @ThomasDecaux that's actually not so strange at all, because a `__toString()` method would need to know which format to convert the `DateTime` object to, and there are probably hundreds of possible formats out there. Of course, in PHP you can use the [`format()`](https://php.net/manual/en/datetime.format.php) method on a `DateTime` object, which takes a format argument, and the `date` filter is simply the Twig equivalent of that method. – Nic Wortel Oct 16 '14 at 08:53
76

It depends on the format you want the date to be shown as.

Static date format

If you want to display a static format, which is the same for all locales (for instance ISO 8601 for an Atom feed), you should use Twig's date filter:

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

Which will allways return a datetime in the following format:

2014-05-02T08:55:41Z

The format strings accepted by the date filter are the same as you would use for PHP's date() function. (the only difference is that, as far as I know, you can't use the predefined constants which can be used in the PHP date() function)

Localized dates (and times)

However, since you want to render it in the browser, you'll likely want to show it in a human-readable format, localised for the user's language and location. Instead of doing the localization yourself, you can use the Intl Extension for this (which makes use of PHP's IntlDateFormatter). It provides a filter localizeddate which will output the date and time using a localized format.

localizeddate( date_format, time_format [, locale ] )

Arguments for localizeddate:

  • date_format: One of the format strings (see below)
  • time_format: One of the format strings (see below)
  • locale: (optional) Use this to override the configured locale. Leave this argument out to use the default locale, which can be configured in Symfony's configuration.

(there are more, see the docs for the complete list of possible arguments)

For date_format and time_format you can use one of the following strings:

  • 'none' if you don't want to include this element
  • 'short' for the most abbreviated style (12/13/52 or 3:30pm in an English locale)
  • 'medium' for the medium style (Jan 12, 1952 in an English locale)
  • 'long' for the long style (January 12, 1952 or 3:30:32pm in an English locale)
  • 'full' for the completely specified style (Tuesday, April 12, 1952 AD or 3:30:42pm PST in an English locale)

Example

So, for instance, if you want to display the date in a format equivalent to February 6, 2014 at 10:52 AM, use the following line in your Twig template:

{{ game.gameDate|localizeddate('long', 'short') }}

However, if you use a different locale, the result will be localized for that locale:

  • 6 februari 2014 10:52 for the nl locale;
  • 6 février 2014 10:52 for the fr locale;
  • 6. Februar 2014 10:52 for the de locale; etc.

As you can see, localizeddate does not only translate the month names but also uses the local notations. The English notation puts the date after the month, where Dutch, French and German notations put it before the month. English and German month names start with an uppercase letter, whereas Dutch and French month names are lowercase. And German dates have a dot appended.

Installation / setting the locale

Installation instructions for the Intl extension can be found in this seperate answer.

Nic Wortel
  • 11,155
  • 6
  • 60
  • 79
8

I know this is a pretty old question, but I found this question today, but the answers were not what I needed.

So here's what I needed.

If you, like me, are looking to display the current date in twig, you can use the following:

{{ "now"|date("m/d/Y") }}

See documentation about this:

date in twig

Refilon
  • 3,334
  • 1
  • 27
  • 51
7

To avoid error on null value you can use this code:

{{ game.gameDate ? game.gameDate|date('Y-m-d H:i:s') : '' }}
Arnold Richmon
  • 321
  • 3
  • 8
4

Dont forget

@ORM\HasLifecycleCallbacks()

Entity :

/**
     * Set gameDate
     *
     * @ORM\PrePersist
     */
    public function setGameDate()
    {
        $this->dateCreated = new \DateTime();

        return $this;
    }

View:

{{ item.gameDate|date('Y-m-d H:i:s') }}

>> Output 2013-09-18 16:14:20

Ivan
  • 5,139
  • 11
  • 53
  • 86
3
{{game.gameDate | date('c')}}  // 2014-02-05T16:45:22+00:00

For full date time string including timezone offset.

Venkat Kotra
  • 10,413
  • 3
  • 49
  • 53
2

There is a symfony2 tool to display date in the current locale:

{{ user.createdAt|localeDate }} to have a medium date and no time, in the current locale

{{ user.createdAt|localeDate('long','medium') }} to have a long date and medium time, in the current locale

https://github.com/michelsalib/BCCExtraToolsBundle

ihsan
  • 2,279
  • 20
  • 36
2

you can render in following way

{{ post.published_at|date("m/d/Y") }}

For more details can visit http://twig.sensiolabs.org/doc/filters/date.html

Zaheer Babar
  • 1,636
  • 1
  • 15
  • 17
2

You can use the function date and ternary operator of twig

{{ game.gameDate ? game.gameDate|date('d-m-Y H:i') : 'Not Available' }}
L3xpert
  • 1,109
  • 1
  • 10
  • 19
0

New format_datetime filter (2022)

In twig 3, use format_datetime filter.

It also supports localization and custom pattern (ICU).


{# 07/08/2019 #}
{{ '2019-08-07 23:39:12'|format_datetime('short', 'none', locale='fr') }}

{# mercredi 7 août 2019 23:39:12 UTC #}
{{ '2019-08-07 23:39:12'|format_datetime('full', 'full', locale='fr') }}

source : https://twig.symfony.com/doc/3.x/filters/format_datetime.html

Ousmane
  • 2,673
  • 3
  • 30
  • 37