2

I am using the Dukt Twitter plugin and want to display the time since the tweet was created.

The Twitter API returns a string in the format:

Fri Sep 02 14:42:42 +0000 2016

I can use the date filter on this string to alter the format, but cannot pass this through the diff method that twig exposes. I think I need to create a dateTime object, would this require a plugin to be created for this task or can I achieve this in twig?

A reference post on this forum discusses the diff method: Get Age from Date of Birth - however I think I need to have a date object, not a string, to use it. Ideally I'd like to just achieve this in twig as I have never written a plugin before! Thanks

2

You can use the date method for creating a date object. e.g.: {% set tweetDate = date("Fri Sep 02 14:42:42 +0000 2016") %}

2

Great! Thank you @techgyver

Here is my final code:

{% for tweet in tweets %}
{% set tweetDate = date(tweet.created_at).diff(now).format('%a') %}
    {% if tweetDate == 0 %}
        {% set tweetTimeAgo = 'today' %}
    {% else %}
        {% set tweetTimeAgo = tweetDate ~ ' days ago' %}
    {% endif %}

<div class="tweet-time">{{ tweetTimeAgo }}</div>
<div class="tweet-text">{{ tweet.text|autoLinkTweet }}</div>
{% endfor %}

Which either outputs 'today' or '3 days ago' depending on diff since tweet.

2

Further to Adam's answer, and for everyone else who is reading this question, there is a Craft plugin that can do the date calculation logic, as well as providing more readable timestamps:

https://github.com/blue-mantis/BM-Time-Ago-In-Words.

As well as '...days ago' it extends into weeks and months, which may not be as useful in this scenario but could prove more useful for blog/news sections.

1
  • Thanks that is a great plugin by the sounds of it, improving the functionality of my original question – Adam Menczykowski Sep 5 '16 at 12:43

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.