Search code examples
javaandroiddatetimedatetwitter

Android calculating minutes/hours/days from point in time


I am parsing twitters and i want to display how long ago it was since the twitter was posted. But it doesn't seem to be calculating correctly. I got the formula from another post here on Stackoverflow and i tried to build the return statement from it.

public static String getTwitterDate(Date date){
    long milliseconds = date.getTime();
    int minutes = (int) ((milliseconds / (1000*60)) % 60);
    int hours   = (int) ((milliseconds / (1000*60*60)) % 24);

    if (hours > 0){
        if (hours == 1)
            return "1 hour ago";
        else if (hours < 24)
            return String.valueOf(hours) + " hours ago";
        else
        {
            int days = (int)Math.ceil(hours % 24);
            if (days == 1)
                return "1 day ago";
            else
                return String.valueOf(days) + " days ago";
        }
    }
    else
    {
        if (minutes == 0)
            return "less than 1 minute ago";
        else if (minutes == 1)
            return "1 minute ago";
        else
            return String.valueOf(minutes) + " minutes ago";
    }
}

Parsing the twitter date/time with this (also from a post on Stackoverflow)

public static Date parseTwitterDate(String date)
{
    final String TWITTER = "EEE, dd MMM yyyy HH:mm:ss Z";
    SimpleDateFormat sf = new SimpleDateFormat(TWITTER, Locale.ENGLISH);
    sf.setLenient(true);

    try {
        return sf.parse(date);
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return null;
}

Example of a twitter date: "created_at":"Sat, 30 Jun 2012 14:44:40 +0000",

As far as i can tell, the twitters are getting parsed correctly but not calculated correctly (getTwitterDate). That returns 11 hours some times when its a difference of 4-5 hours.


Solution

  • long milliseconds = date.getTime() - new Date().getTime();

    that will run the calculation based on the difference between the date of the tweet and now.

    At the moment, you are basing your calculation on date.getTime() which is the number of milliseconds since midnight on 1-Jan-1970. Because you also introduces modulos, your current function gives you the time elapsed between midnight UTC and the tweet.