(Treehouse Code Snippet) Calculating days/months/years ago

Something I need to do from time to time is replicate the “days ago” feature that was built into BC.

This is what I’ve come up with:

{% assign nowSecond="now" | date: "%s" %}

{% assign daysAgo = this['ReleaseDate'] | date: "%s" | minus: nowSecond | divided_by: 3600 | divided_by: 24 | round | replace: '-', '' %}

{% assign monthsAgo = daysAgo | divided_by: 30.43 | round | replace: '-', '' %}

{% assign yearsAgo = monthsAgo | divided_by: 12 | round | replace: '-', '' %}

{% if monthsAgo >= 12 %}

{{yearsAgo}} year{% if yearsAgo > 1 %}s{% endif %}

{% elsif monthsAgo >= 1 %}

{{monthsAgo}} month{% if monthsAgo > 1 %}s{% endif %}

{% else %}

    {{daysAgo}} day{% if daysAgo > 1 %}s{% endif %}

{% endif %}

 ago

I’d like to get this added to the Treehouse code snippets as I thought it would be useful for others, but I thought perhaps somebody had a slicker way of doing this.

If you have a better way of doing this or suggestions, I’d appreciate the feedback.

Hi @Alex_B_Centrifuge
I actually already had something very similar on my list to post to the Treehouse site from @James (as per this Slack thread: https://treepl.slack.com/messages/CC1074CQM/p1621300167000700)

However, there are things I like about both.
I like yours due to:

  • being more readable/understandable.
  • creates variable you can use for all periods (days/months/years) so you can use any/all period types regardless of the date difference.

I like Jame’s due to:

  • covers sec/min/hr/days/mths/yrs (I added ‘weeks’)
  • the separation of logic from markup

So I added some bits and combined all into one ‘super snippet’ :slight_smile:
Let me know if you can see any improvements to make / flaws to fix:

1 Like

Great work you guys! :+1:
Love the term “Super Snippet” :muscle:

Fantastic @Adam.Wilson! Looks great.