我得到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;
我需要一些使用更智能方法的工作代码,甚至是需要使用工作解决方案的任何方法。帮我解决一下。
答案 0 :(得分:1)
我认为你应该使用Calendar
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);
Calendar实现了Comparable ......
long subs = Math.abs(cal.getTimeInMillis() c.getTimeInMillis());
Calendar subCalendar = (Calendar)cal.clone();
subCalendar.setTimeInMillis(subs);
您也可以使用this link, because it seems to be a problem like yours