Android从时间点计算分钟/小时/天

时间:2012-06-30 14:51:26

标签: java android datetime date twitter

我正在解析twitters,我想显示自推特发布以来多久以来。但它似乎没有正确计算。我从Stackoverflow上的另一个帖子得到了公式,我试图从它构建return语句。

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";
    }
}

使用此解析推特日期/时间(也来自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;
}

推特日期示例:“created_at”:“星期六,2012年6月30日14:44:40 +0000”,

据我所知,twitters正确解析但未正确计算(getTwitterDate)。当它相差4-5小时时,有时会返回11个小时。

5 个答案:

答案 0 :(得分:10)

使用DateUtils。它完全本地化,以人性化的方式做你想做的事。

以下是获取自动本地化的相对时间跨度表达式的示例:

long time = ... // The Twitter post time stamp
long now = System.currentTimeMillis();
CharSequence relativeTimeStr = DateUtils.getRelativeTimeSpanString(time, 
    now, DateUtils.SECOND_IN_MILLIS, DateUtils.FORMAT_ABBREV_RELATIVE);

产生“10秒前”或“5分钟”等输出。

答案 1 :(得分:4)

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

将根据推文日期与现在之间的差异进行计算。

目前,您的计算基于date.getTime(),这是自1970年1月1日午夜以来的毫秒数。因为您还引入了模数,所以您当前的函数会为您提供午夜UTC和推文之间的时间。

答案 2 :(得分:3)

你可以修改输入变量“timeAtMiliseconds”,因为我的例子是日期格式为毫秒。

private static SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private static SimpleDateFormat formatterYear = new SimpleDateFormat("MM/dd/yyyy");

public static String parseDate(@NotNull Long timeAtMiliseconds) {
    timeAtMiliseconds *= 1000L; //Check if this is unnecessary for your use

    if (timeAtMiliseconds == 0) {
        return "";
    }

    //API.log("Day Ago "+dayago);
    String result = "now";
    String dataSot = formatter.format(new Date());
    Calendar calendar = Calendar.getInstance();

    long dayagolong = timeAtMiliseconds;
    calendar.setTimeInMillis(dayagolong);
    String agoformater = formatter.format(calendar.getTime());

    Date CurrentDate = null;
    Date CreateDate = null;

    try {
        CurrentDate = formatter.parse(dataSot);
        CreateDate = formatter.parse(agoformater);

        long different = Math.abs(CurrentDate.getTime() - CreateDate.getTime());

        long secondsInMilli = 1000;
        long minutesInMilli = secondsInMilli * 60;
        long hoursInMilli = minutesInMilli * 60;
        long daysInMilli = hoursInMilli * 24;

        long elapsedDays = different / daysInMilli;
        different = different % daysInMilli;

        long elapsedHours = different / hoursInMilli;
        different = different % hoursInMilli;

        long elapsedMinutes = different / minutesInMilli;
        different = different % minutesInMilli;

        long elapsedSeconds = different / secondsInMilli;

        if (elapsedDays == 0) {
            if (elapsedHours == 0) {
                if (elapsedMinutes == 0) {
                    if (elapsedSeconds < 0) {
                        return "0" + " s";
                    } else {
                        if (elapsedSeconds > 0 && elapsedSeconds < 59) {
                            return "now";
                        }
                    }
                } else {
                    return String.valueOf(elapsedMinutes) + "m ago";
                }
            } else {
                return String.valueOf(elapsedHours) + "h ago";
            }

        } else {
            if (elapsedDays <= 29) {
                return String.valueOf(elapsedDays) + "d ago";
            }
            if (elapsedDays > 29 && elapsedDays <= 58) {
                return "1Mth ago";
            }
            if (elapsedDays > 58 && elapsedDays <= 87) {
                return "2Mth ago";
            }
            if (elapsedDays > 87 && elapsedDays <= 116) {
                return "3Mth ago";
            }
            if (elapsedDays > 116 && elapsedDays <= 145) {
                return "4Mth ago";
            }
            if (elapsedDays > 145 && elapsedDays <= 174) {
                return "5Mth ago";
            }
            if (elapsedDays > 174 && elapsedDays <= 203) {
                return "6Mth ago";
            }
            if (elapsedDays > 203 && elapsedDays <= 232) {
                return "7Mth ago";
            }
            if (elapsedDays > 232 && elapsedDays <= 261) {
                return "8Mth ago";
            }
            if (elapsedDays > 261 && elapsedDays <= 290) {
                return "9Mth ago";
            }
            if (elapsedDays > 290 && elapsedDays <= 319) {
                return "10Mth ago";
            }
            if (elapsedDays > 319 && elapsedDays <= 348) {
                return "11Mth ago";
            }
            if (elapsedDays > 348 && elapsedDays <= 360) {
                return "12Mth ago";
            }

            if (elapsedDays > 360 && elapsedDays <= 720) {
                return "1 year ago";
            }

            if (elapsedDays > 720) {
                Calendar calendarYear = Calendar.getInstance();
                calendarYear.setTimeInMillis(dayagolong);
                return formatterYear.format(calendarYear.getTime()) + "";
            }

        }

    } catch (java.text.ParseException e) {
        e.printStackTrace();
    }
    return result;
}

      //USAGE
    Log.d("TAG Pretty date: ", parseDate(System.currentTimeMillis()));

答案 3 :(得分:0)

现在有一天推特时间响应如下: 星期四03月05日03:13:48 +0000 2015

我将它们转换为 5秒前/ 5分钟前/ 5小时前/ 5天前 来调用服装功能:

public void TwitterTimeDifferentitaion(String responseTime) {

SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM dd HH:mm:ss Z yyyy");
                    ParsePosition pos = new ParsePosition(0);
                    long then = formatter.parse(responseTime, pos).getTime();
                    long now = new Date().getTime();

                    long seconds = (now - then) / 1000;
                    long minutes = seconds / 60;
                    long hours = minutes / 60;
                    long days = hours / 24;

                    String friendly = null;
                    long num = 0;
                    if (days > 0) {
                        num = days;
                        friendly = days + " day";
                    }
                    else if (hours > 0) {
                        num = hours;
                        friendly = hours + " hour";
                    }
                    else if (minutes > 0) {
                        num = minutes;
                        friendly = minutes + " minute";
                    }
                    else {
                        num = seconds;
                        friendly = seconds + " second";
                    }
                    if (num > 1) {
                        friendly += "s";
                    }
                    createdAt = friendly + " ago";
                    System.out.println("TotalTime>>" + createdAt);

}  

每当响应格式改变而不是SimpleDateFormat()时也改变&amp;工作完美.. !!!

答案 4 :(得分:-1)

long daysDifference = calender01.getTime()-calender02.getTime();

                            if (TimeUnit.MILLISECONDS.toHours(daysDifference) <= 24) {
                                if (TimeUnit.MILLISECONDS.toHours(daysDifference) == 0) {
                                    long days = TimeUnit.MILLISECONDS.toMinutes(daysDifference);
                                    dayCounter.setText(days + " minute(s) more");
                                } else {
                                    long days = TimeUnit.MILLISECONDS.toHours(daysDifference);
                                    dayCounter.setText(days + " hours(s) more");
                                }
                            } else {
                                long days = TimeUnit.MILLISECONDS.toDays(daysDifference + 24 * 60 * 60 * 1000);
                                dayCounter.setText(days + " day(s) more");
                            }