Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Time-Ago Twig Macro
{# Based on this StackOverflow example: https://stackoverflow.com/a/26311354/1272059 #}
{% macro time_ago(timestamp) %}
{% set lapse = date().getTimestamp() - timestamp %}
{% set units = {
'year': 31536000,
'month': 2592000,
'week': 604800,
'day': 86400,
'hour': 3600,
'minute': 60,
'second': 1,
}
%}
<span class="friendlyDate">
{% set foundVal = false %}
{% for val,unit in units %}
{% if not foundVal and lapse >= unit %}
{% set foundVal = true %}
{% if val == 'second' %}
a few seconds ago
{% else %}
{% set numberOfUnits = lapse // unit %}
{% if numberOfUnits > 1 %}
{{ numberOfUnits }} {{ val }}s ago
{% else %}
a {{ val }} ago
{% endif %}
{% endif %}
{% endif %}
{% endfor %}
</span>
{% endmacro %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.