我得到一个unix timeStamp,我需要计算当前时间和给定的unix时间戳之间的差异,如:
2 sec ago
5 mins ago
2 hours ago
3 days ago
所以我写了下面的代码:
String time = "given unix timeStamp";
Date date = new Date();
date.setTime(Long.parseLong(time) * 1000);
Calendar start = Calendar.getInstance();
start.setTime(date); // given time
Calendar end = Calendar.getInstance();
end.setTime(new Date()); // current time
Integer[] elapsed = new Integer[6];
Calendar clone = (Calendar) start.clone();
elapsed[0] = elapsed(clone, end, Calendar.YEAR);
clone.add(Calendar.YEAR, elapsed[0]);
elapsed[1] = elapsed(clone, end, Calendar.MONTH);
clone.add(Calendar.MONTH, elapsed[1]);
elapsed[2] = elapsed(clone, end, Calendar.DATE);
clone.add(Calendar.DATE, elapsed[2]);
elapsed[3] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 3600000;
clone.add(Calendar.HOUR, elapsed[3]);
elapsed[4] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 60000;
clone.add(Calendar.MINUTE, elapsed[4]);
elapsed[5] = (int) (end.getTimeInMillis() - clone.getTimeInMillis()) / 1000;
submissionTime.setText(elapsed[0] + " years," + elapsed[1] + " months,"
+ elapsed[2] + " days," + elapsed[3] + " hours," + elapsed[4]
+ " minutes," + elapsed[5] + " seconds");
这是elapsed()
函数:
public static int elapsed(Calendar before, Calendar after, int field) {
Calendar clone = (Calendar) before.clone();
int elapsed = -1;
while (!clone.after(after)) {
clone.add(field, 1);
elapsed++;
}
return elapsed;
}
但这给了我错误的输入。我是Java / Android日期操作的新手,一些完整的工作代码会很有帮助。