3

I am trying to print if statement for x time or x day ago for each published entries. For example the entry is posted x minutes ago should display x minutes ago or x hours ago. Same for days and months.

Here is what I have used but not what I am after.

{{ date(category.dateCreated|date('c')).diff(now).format('%a') }}

But the code I have written does not work.

{% for category in entries %}

{% for time in category %}
<span>{{ date(time.dateCreated|date('c')).diff(now).format('%i') }} minutes ago</span>

{% else %}
<span>{{ date(time.dateCreated|date('c')).diff(now).format('%h') }} hours ago</span>

{% else %}
<span>{{ date(time.dateCreated|date('c')).diff(now).format('%d') }} days  agos</span>
{% endfor %}
{% endfor %}

The above code is too long or is there a better way to check whether the entry is posted min, hours, or days ago.

  • 2
    Check out the DateTimeHelper method timeAgoInWords. It will do what you are after. craftcms.com/classreference/helpers/… – Fyrebase Mar 20 '17 at 3:25
  • @Fyrebase Well I learned something today. You should post this as an answer. – Stephen Lewis Mar 20 '17 at 8:27
  • Any idea what the Craft 3 version of timeAgoInWords() is? – Sandwich Jun 4 '18 at 15:02
4

Check out the DateTimeHelper method timeAgoInWords. It will do what you are after.

https://craftcms.com/classreference/helpers/DateTimeHelper#timeAgoInWords-detail

There is even a handy twig filter available for use in your templates.

{{ entry.dateCreated|timeAgoInWords }}

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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