Brien12
Brien12

Reputation: 25

Trying to convert a date in Twig

I'm trying to convert this:

{{ "26/03/2013"|date("d/m/Y") }}

in Twig but its is throwing the error

Uncaught Exception: DateTime::__construct(): Failed to parse time string (26/03/2013) at position 0 (2): Unexpected character in /home/vagrant/Code/Phantom Website/vendor/twig/twig/lib/Twig/Template.php on line 218.

If I pass this:

{{ "03/26/2013"|date("m/d/Y") }}

It works, so I imagine I need to change something related to Twigs date formatting

Upvotes: 1

Views: 6033

Answers (2)

Matteo
Matteo

Reputation: 39370

The date filter is about formatting DateTime Object, so if you pass a string this will be passed to the constructor of the DateTime object then to the format method, so in your case, you need to format the string that looks good for a DateTime constructor as example

{{ "2013-3-26"|date("d/m/Y") }}

From the doc:

The format specifier is the same as supported by date, except when the filtered data is of type DateInterval, when the format must conform to DateInterval::format instead.

And also about string format:

The date filter accepts strings (it must be in a format supported by the strtotime function), DateTime instances, or DateInterval instances. For instance, to display the current date, filter the word "now":

Try this in this twigfiddle

Upvotes: 3

DarkBee
DarkBee

Reputation: 15659

If you use /'s as delimiter the expected format is m/d/Y,
To pass the date as day, month, year you need to use a - as delimiter

{{ "26-03-2017" | date('d/m/Y') }}

fiddle

Upvotes: 1

Related Questions