Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
364 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 Reply

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...