I'm trying to format a date and place each item (month, day and year) inside a div or span. I'm using a SaaS platform which provide a date like so:
2015-03-07 22:54:00
What I try to do is format this date into 3 separate items and place them in a div like so:
<span class="day">07</span>
<span class="month">March</span>
<span class="year">2015</span>
Therefore I need to strip everything behind a -
and call it inside a div like so:
<span class="day">{{ article.date | split('-')[2] }}</span>
<span class="month">{{ article.date | split('-')[1] }}</span>
<span class="year">{{ article.date | split('-')[0] }}</span>
This gives me an output like:
<span class="day">07 22:54:00</span>
<span class="month">03</span>
<span class="year">2015</span>
Where I get stuck is to remove the time after the day and change the month into a textual representation.
I know it can be done with PHP date functions but I can't get that to work. The problem I'm facing is that the date needs to be stripped after each -
.
Is there anybody who can help me with that?
You can use the date()
function, and then the date
filter
NB: they are 2 really different things!!!
{% set dateTime = date(article.date) %}
<span class="day">{{ dateTime | date('d') }}</span>
<span class="month">{{ dateTime | date('F') }}</span>
<span class="year">{{ dateTime | date('Y') }}</span>
First, the date()
function converts your string dates to a DateTime object.
Then, the date
filter makes you do the equivalent of the DateTime::format
PHP function, so you can use a separate notation for the desidered output.
If you need to translate the name of the month to a locale, you can pipe the trans
filter, but it must be enabled first.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With