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

Adam Menczykowski
  • 1,390
  • 11
  • 22

3 Answers3

3

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.

Adam Menczykowski
  • 1,390
  • 11
  • 22
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") %}

techgyver
  • 21
  • 1
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.

Jamie Wade
  • 3,644
  • 2
  • 16
  • 32