Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I display a formatted date from a Unix timestamp in twig?

Tags:

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?

like image 353
Bogdan Avatar asked Aug 17 '12 10:08

Bogdan


People also ask

How do I turn a timestamp into a date?

You can simply use the fromtimestamp function from the DateTime module to get a date from a UNIX timestamp. This function takes the timestamp as input and returns the corresponding DateTime object to timestamp.

How do you get the current date in twig?

The first thing we need to do is get today. We do that using the now string in Twig. We can pass this string through the date filter and get a string of today's date.

How do I read a Unix timestamp?

To find the unix current timestamp use the %s option in the date command. The %s option calculates unix timestamp by finding the number of seconds between the current date and unix epoch.

How are timestamps formatted?

TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC. A DATETIME or TIMESTAMP value can include a trailing fractional seconds part in up to microseconds (6 digits) precision. With the fractional part included, the format for these values is ' YYYY-MM-DD hh:mm:ss [.


2 Answers

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 -->
like image 128
Florent Avatar answered Sep 21 '22 13:09

Florent


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.

like image 45
greg Avatar answered Sep 22 '22 13:09

greg