21

I would like to display a formatted date in twig by applying a filter to a Unix timestamp. Is such a feature available in twig?

Bogdan
  • 913
  • 2
  • 12
  • 29

2 Answers2

30

There is a filter called date.

In the following example mydate equals 1286199900:

{{ mydate|date }}           <!-- October 4, 2010 13:45 -->
{{ mydate|date('d/m/Y') }}  <!-- 04/10/2010 -->
Florent
  • 12,310
  • 10
  • 49
  • 58
  • Yes, I figured out that actually the date filter does handle Unix timestamps only I was providing the 13-digit timestamp instead of the 10-digit one and that confused the filter. I don't suppose there is a simple way of handling 13-digit timestamps with the date filter, isn't there? – Bogdan Aug 17 '12 at 11:10
  • 2
    Maybe `{% set newdate = mydate / 1000 %}{{ newdate|date }}` – Florent Aug 17 '12 at 11:25
  • 1
    That never even crossed my mind. Thank you, it worked like a charm. – Bogdan Aug 17 '12 at 11:40
  • This doesn't work in Jtwig (Java). It throws an exception. Expects a Date object or "now" strinig. – TheRealChx101 Jun 04 '19 at 16:02
  • Wonder if the date filter will automatically translate in the right langage ? – snoob dogg Oct 31 '19 at 14:18
6

If you just divide it by 1000 there might be an error like Failed to parse time string (1384361503.5) at position 7

I would add round function to it

{% set timestamp = (rating.ratingDate / 1000)|round(0, 'floor') %} {{timestamp|date('d. M Y')}}

I know I am playing an archaeologist but it might be helpful for someone.

greg
  • 1,857
  • 2
  • 20
  • 32