我有以下代码成功地让我了解了两天之间的差异(以天、小时、分钟、秒为单位):
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-DD HH:mm:ss");
Date d1 = format.parse(startTime);
Date d2 = format.parse(endTime);
long diff = d2.getTime() - d1.getTime();
long diffSeconds = diff / 1000 % 60;
long diffMinutes = diff / (60 * 1000) % 60;
long diffHours = diff / (60 * 60 * 1000) % 24;
long diffDays = diff / (24 * 60 * 60 * 1000);
System.out.println("Start: " + startTime);
System.out.println("End: " + endTime);
System.out.println(diffDays + " days, " + diffHours + " hours, " + diffMinutes + " minutes, " + diffSeconds + " seconds");
但是,当日期跨入另一个月份时,这不起作用,例如:
Start: 2013-07-31 10:15:01
End: 2013-08-01 11:22:33
-29 days, -22 hours, -52 minutes, -28 seconds
Start: 2013-05-31 10:15:01
End: 2013-08-01 11:22:33
-29 days, -22 hours, -52 minutes, -28 seconds
是否可以智能跨越数月并获得准确的时差?我对 Joda 很熟悉,但我想坚持使用标准的 Java API,除非没有 Joda 这样的东西是不可能的。