Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
346 views
in Technique[技术] by (71.8m points)

java - Difference of two Joda LocalDateTimes

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

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.

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.

Thanks in advance!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use org.joda.time.Period class for this - in particular the fieldDifference method.

Example:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...