我有一个约会。想把它与当前日期进行比较,并希望得到结果。
Date d1 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
getParameter(date1));
Date d2 = new SimpleDateFormat("yyyy-M-dd").parse((String) request.
getParameter(date2));
long diff = d2.getTime() - d1.getTime();
并希望在以前的格式中有这种差异。
例如。 3小时2分钟前
答案 0 :(得分:2)
答案 1 :(得分:1)
如果您只想使用核心Java而不是使用数字文字污染您的代码:
long diffInMillis = d2.getTime() - d1.getTime();
long diffInHours = TimeUnit.MILLISECONDS.toHours(diffInMillis);
long diffInMins = TimeUnit.MILLISECONDS.toMinutes(diffInMillis);
System.out.printf("%d hours %d mins ago%n", diffInHours, (diffInMins - TimeUnit.HOURS.toMinutes(diffInHours)));
答案 2 :(得分:0)
你的长值是毫秒,所以
int min= (int) ((diff / (1000*60)) % 60);
int sec= (int) (diff / 1000) % 60 ;
答案 3 :(得分:0)
尝试,
long diff = d2.getTime() - d1.getTime();
long m= diff/(60*1000);
long hour=m/60;
long minutes=m%60;
System.out.printf("%d hours %d mins ago%n", hour, minutes)
答案 4 :(得分:0)
以下是根据您的要求获取的另一种方法,但不推荐使用getHours()
和getMinutes()
只需做System.out.println((d2.getHours()-d1.getHours())+" hours " +(d2.getMinutes()-d2.getMinutes()) +" mins ago"
);
答案 5 :(得分:0)
friends.i我们可以这样做,我的代码:
public static String getIntervalUpdateTime(long intervalTime) {
StringBuilder result = new StringBuilder();
long interval = intervalTime / 1000;
final long day = 24 * 60 * 60;
final long hour = 60 * 60;
final long minute = 60;
int detailDay = 0;
int detailHour = 0;
int detailMinute = 0;
int detailSecond = 0;
if (interval >= day) {
detailDay = (int) (interval / day);
interval = interval - detailDay * day;
}
if (interval >= hour) {
detailHour = (int) (interval / hour);
interval = interval - hour * detailHour;
}
if (interval >= minute) {
detailMinute = (int) (interval / minute);
interval = interval - detailMinute * minute;
}
if (interval > 0) {
detailSecond = (int) interval;
}
result.setLength(0);
if (detailDay > 0) {
result.append(detailDay);
result.append("day");
}
if (detailHour > 0) {
result.append(detailHour);
result.append("hour");
}
if (detailMinute > 0) {
result.append(detailMinute);
result.append("minutes");
}
if (detailSecond > 0) {
result.append(detailSecond);
result.append("seconds");
}
return result.toString();
}
这是我的答案。
答案 6 :(得分:0)
使用专为此目的而构建的Period 2.3中的Joda-Time课程。
请参阅问题this one的答案中的示例代码(尤其是How to calculate elapsed time from now with Joda-Time?)。