两个Joda LocalDateTimes的差异 [英] Difference of two Joda LocalDateTimes

查看:289
本文介绍了两个Joda LocalDateTimes的差异的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got 2 Joda LocalDateTime objects and need to produce a 3rd that represents the difference between them:

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

LocalDateTime diff = ???

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

The only way I can figure is to painstakingly go through each date/time field and performs its respective minus operation:

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());

最终结果只是调用 diff 's toString()方法并获得有意义的东西。例如,如果 start.toString()生成2012/02 / 08T15:05:00,并且 end.toString()生产2012/02 / 08T16:00:00,然后 diff.toString()将是差异(55分钟),可能看起来像2012/02 / 08T00:55 :00。

The end result would simply be to call diff's toString() method and get something meaningful. For instance if start.toString() produces 2012/02/08T15:05:00, and end.toString() produces 2012/02/08T16:00:00, then diff.toString() would be the difference (55 minutes) and might look like 2012/02/08T00:55:00.

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

And, if this is a terrible abuse of LocalDateTime, then I just need to know how to take the time difference between the two and put that difference into an easy-to-read (human friendly) format.

提前致谢!

推荐答案

您可以使用org.joda.time.Period类。了解更多关于org.joda.time.Period的信息

You can use org.joda.time.Period class for this. Read more about org.joda.time.Period

示例:

LocalDateTime endOfMonth = now.dayOfMonth().withMaximumValue();
LocalDateTime firstOfMonth = now.dayOfMonth().withMinimumValue();
Period.fieldDifference(firstOfMonth, endOfMonth)

这篇关于两个Joda LocalDateTimes的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆