两个Joda LocalDateTimes的差异

IAm*_*aja 10 java jodatime

我有2个Joda LocalDateTime对象,需要生成一个表示它们之间差异的第3个:

LocalDateTime start = getStartLocalDateTime();
LocalDateTime end = getEndLocalDateTime();

LocalDateTime diff = ???
Run Code Online (Sandbox Code Playgroud)

我能想到的唯一方法是精心遍历每个日期/时间字段并执行其各自的minus操作:

LocalDateTime diff = end;

diff.minusYears(start.getYear());
diff.minusMonths(start.getMonthOfYear());
diff.minusDays(start.getDayOfMonth());
diff.minusHours(start.getHourOfDay());
diff.minusMinutes(start.getMinuteOfHour());
diff.minusSeconds(start.getSecondsOfMinute());
Run Code Online (Sandbox Code Playgroud)

最终的结果将仅仅是调用difftoString()方法,并得到一些有意义的事.例如,如果start.toString()生产2012/02/08T15:05:00,并end.toString()生成2012/02/08T16:00:00,那么diff.toString()差异(55分钟)可能看起来像2012/02/08T00:55:00.

而且,如果这是一个可怕的滥用LocalDateTime,那么我只需要知道如何消除两者之间的时差,并将这种差异变成易于阅读(人性化)的格式.

提前致谢!

Ily*_*lya 18

您可以使用org.joda.time.Period类.阅读更多关于org.joda.time.Period的信息

例:

LocalDateTime endOfMonth = now.dayOfMonth().withMaximumValue();
LocalDateTime firstOfMonth = now.dayOfMonth().withMinimumValue();
Period period = Period.fieldDifference(firstOfMonth, endOfMonth)
Run Code Online (Sandbox Code Playgroud)

  • 我喜欢Joda,但我总是不知所措.`Period`和`Duration`,听起来很像,但却完全不同.我看到了需要,但并不总是直观的. (6认同)
  • [API Doc for Period](http://joda-time.sourceforge.net/apidocs/org/joda/time/Period.html) (2认同)

kbe*_*bec 9

对于某些情况,持续时间更好.您可以通过此技巧获得与LocalDateTimes(在本地时间线中)一起使用的"与时区无关"的持续时间:

public static Duration getLocalDuration(LocalDateTime start, LocalDateTime end) {
    return new Duration(start.toDateTime(DateTimeZone.UTC), end.toDateTime(DateTimeZone.UTC));
}
Run Code Online (Sandbox Code Playgroud)