我有一个功能:
public String getTimePast(Date d) {
//insertcodehere
}
它接受消息的日期,并且必须以特定格式返回基于当前时间的过去时间。例如,如果它刚刚发布,它会说“现在”
如果是4分钟,就会说“4分钟”
如果是23小时,它会说“23小时”
等
下面是我如何试图做它没有运气!我怎么能做到这一点?谢谢您!
public String getTimePast(Date d) {
Calendar c = Calendar.getInstance();
int hr = c.get(Calendar.HOUR_OF_DAY);
int min = c.get(Calendar.MINUTE);
int day = c.get(Calendar.DAY_OF_MONTH);
int month = c.get(Calendar.MONTH);
int year = c.get(Calendar.YEAR);
if (year == d.getYear()) {
if (month == d.getMonth()) {
if (day == d.getDay()) {
if (hr == d.getHours()) {
if (min == d.getMinutes()) {
return "Now";
} else {
return min - d.getMinutes() + "m";
}
} else {
return hr - d.getHours() + "hr";
}
} else {
return day - d.getDay() + "d";
}
} else {
return month - d.getMonth() + "m";
}
} else {
return year - d.getYear() + "y";
}
}
最佳答案
不如使用另一个日历对象作为简单的差异
Calendar now = Calendar.getInstance();
Calendar start = Calendar.getInstance();
start.setTime (d);
long milliseconds1 = start.getTimeInMillis();
long milliseconds2 = now.getTimeInMillis();
long diff = milliseconds2 - milliseconds1;
long diffSeconds = diff / 1000;
long diffMinutes = diff / (60 * 1000);
long diffHours = diff / (60 * 60 * 1000);
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("\nThe Date Different Example");
System.out.println("Time in milliseconds: " + diff
+ " milliseconds.");
System.out.println("Time in seconds: " + diffSeconds
+ " seconds.");
System.out.println("Time in minutes: " + diffMinutes
+ " minutes.");
System.out.println("Time in hours: " + diffHours
+ " hours.");
System.out.println("Time in days: " + diffDays
+ " days.");
}
参见http://www.roseindia.net/java/beginners/DateDifferent.shtml