Java – Android calculates minutes / hours / days from a point in time

I'm parsing twitter. I want to show how long it's been since twitter was released. But it doesn't seem to calculate correctly. I got the formula from another post on stackoverflow, and I tried to build a 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";
    }
}

Use this to parse twitter date / time (also from posts 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 twitter date: "created_at": "Saturday, June 30, 2012, 14:44:400000",

As far as I know, twitter parses correctly but does not calculate correctly (gettwitterdate). When it differs by 4-5 hours, it sometimes returns 11 hours

resolvent:

long milliseconds = date.getTime() – new Date().getTime();

This will be calculated based on the difference between the tweet date and the present

At present, your calculation is based on date. Gettime (), which is the number of milliseconds since midnight on January 1, 1970. Because you have also introduced modulus, your current function will provide you with the time between midnight UTC and tweet

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>