4

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?

1 Answer 1

11

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.

1
  • 11
    You don't need to use the date() function. You can just use the date filter with a string to cast to a \DateTime object and format like article.date|date('d') or "now"|date('d').
    – qooplmao
    May 7, 2015 at 15:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.