如何在java中找到两个日期之间的差异持续时间?我有两个DateTime对象,需要找到它们的差异持续时间,我有以下代码,但不知道如何继续它以获得预期的结果如下:例 11/03/14 09:30:58 11/03/14 09:33:43 elapsed time is 02 minutes and 45 seconds ----------------------------------------------------- 11/03/14 09:30:58 11/03/15 09:30:58 elapsed time is a day ----------------------------------------------------- 11/03/14 09:30:58 11/03/16 09:30:58 elapsed time is two days ----------------------------------------------------- 11/03/14 09:30:58 11/03/16 09:35:58 elapsed time is two days and 05 mintues码 String dateStart = "11/03/14 09:29:58"; String dateStop = "11/03/14 09:33:43"; Custom date format SimpleDateFormat format = new SimpleDateFormat("yy/MM/dd HH:mm:ss"); Date d1 = null; Date d2 = null; try { d1 = format.parse(dateStart); d2 = format.parse(dateStop); } catch (ParseException e) { e.printStackTrace(); } // Get msec from each, and subtract. long diff = d2.getTime() - d1.getTime(); long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000); System.out.println("Time in seconds: " + diffSeconds + " seconds."); System.out.println("Time in minutes: " + diffMinutes + " minutes."); System.out.println("Time in hours: " + diffHours + " hours.");
3 回答
函数式编程
TA贡献1807条经验 获得超9个赞
尝试以下方法
{ Date dt2 = new DateAndTime().getCurrentDateTime(); long diff = dt2.getTime() - dt1.getTime(); long diffSeconds = diff / 1000 % 60; long diffMinutes = diff / (60 * 1000) % 60; long diffHours = diff / (60 * 60 * 1000); int diffInDays = (int) ((dt2.getTime() - dt1.getTime()) / (1000 * 60 * 60 * 24)); if (diffInDays > 1) { System.err.println("Difference in number of days (2) : " + diffInDays); return false; } else if (diffHours > 24) { System.err.println(">24"); return false; } else if ((diffHours == 24) && (diffMinutes >= 1)) { System.err.println("minutes"); return false; } return true;}
慕尼黑8549860
TA贡献1818条经验 获得超11个赞
可以使用Java内置类TimeUnit以更好的方式处理日期差异转换。它提供了实用方法:
Date startDate = // Set start date
Date endDate = // Set end date
long duration = endDate.getTime() - startDate.getTime();
long diffInSeconds = TimeUnit.MILLISECONDS.toSeconds(duration);
long diffInMinutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long diffInHours = TimeUnit.MILLISECONDS.toHours(duration);
long diffInDays = TimeUnit.MILLISECONDS.toDays(duration);
茅侃侃
TA贡献1842条经验 获得超21个赞
使用Joda-Time库
DateTime startTime, endTime;Period p = new Period(startTime, endTime);long hours = p.getHours();long minutes = p.getMinutes();
Joda Time有一个时间间隔的概念:
Interval interval = new Interval(oldTime, new Instant());
另一个例子 日期差异
还有一个链接
或者使用Java-8(集成了Joda-Time概念)
Instant start, end;//Duration dur = Duration.between(start, stop);long hours = dur.toHours();long minutes = dur.toMinutes();
添加回答
举报
0/150
提交
取消