1

我得到了一个unix timestamp,我需要通过与当前时间比较来找到秒/分钟/小时的差异。我需要类似的东西:

34 sec ago
1 min ago
4 mins ago
5 hours ago
1 days ago
2 days ago

我尝试了一些if-else风格不佳的代码,但它给出了错误的奇怪输出

String time = null;
long quantity = 0;
long addition = 0;
long diffMSec = System.currentTimeMillis() - Long.parseLong(submissionInfo
        .get(CommonUtils.KEY_SUBMISSION_TIME)) * 1000L;
diffMSec /= 1000L;
if (diffMSec < 86400L) { // less than one day
    if (diffMSec < 3600L) { // less than one hour
        if (diffMSec < 60L) { // less than one minute
            quantity = diffMSec;
            time = "sec ago";
        } else { // greater than or equal to one minute
            addition = (diffMSec % 60L) > 0 ? 1 : 0;
            quantity = (diffMSec / 60L) + addition;
            if (quantity > 1)
                time = "mins ago";
            else
                time = "min ago";
        }
    } else { // greater than or equal to one hour
        addition = (diffMSec % 3600L) > 0 ? 1 : 0;
        quantity = (diffMSec / 3600L) + addition;
        if (quantity > 1)
            time = "hours ago";
        else
            time = "hour ago";
    }
} else { // greater than or equal to one day
    addition = (diffMSec % 86400) > 0 ? 1 : 0;
    quantity = (diffMSec / 86400) + addition;
    if (quantity > 1)
        time = "days ago";
    else
        time = "1 day ago";
}
time = quantity + " " + time;

我需要一些具有更智能方法的工作代码,甚至需要任何具有工作解决方案的方法。帮我弄清楚。

4

1 回答 1

1

我认为你应该使用日历

Calendar cal = Calendar.getInstance();

String time = "yourtimestamp";
long timestampLong = Long.parseLong(time)*1000;
Date d = new Date(timestampLong);
Calendar c = Calendar.getInstance();
c.setTime(d);
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int date = c.get(Calendar.DATE);

日历实现了 Comparable 所以...

long subs = Math.abs(cal.getTimeInMillis()  c.getTimeInMillis());
Calendar subCalendar = (Calendar)cal.clone();
subCalendar.setTimeInMillis(subs);

您也可以使用此链接,因为它似乎是您的问题

于 2013-08-08T07:35:54.777 回答