I need help to get the Period between two Java Dates. I use JodaTime for the calculation but the result isn't correct.
Start: 11.11.2012 12:00
End: 16.12.2012 20:15
(German time standard)
Result musst be 5 weeks, 0 days, 8 hours and 15 minutes.
I try it with
Period period = new Period( start.getTime(), end.getTime() );
weeks = Weeks.weeksBetween( new DateTime( start ), new DateTime( end ) ).getWeeks();
days = period.getDays();
hours = period.getHours();
minutes = period.getMinutes();
and got 5w 5d 8h 15m.
EDIT:
Thanks for the help but i think i use the JodaTime Period wrong. Off course is the output of 5w 5d 8h 15m right but what i want is more like this.
int days = Days.daysBetween( start, end ); // musst be 35 days
int weeks = ( days - ( days % 7 ) ) / 7;
days = days % 7;
Now is my result 5 weeks and 0 days. Sorry for the confusion and thanks for the help.
解决方案
DateTime start = new DateTime(new Date(2012, 11, 11, 12, 00, 00));
DateTime end = new DateTime(new Date(2012, 12, 16, 20, 15, 00));
Period period = new Period(start, end);
System.out.println("Weeks: " + Weeks.weeksBetween( new DateTime( start ), new DateTime( end ) ).getWeeks());
System.out.println("Days: " + period.getDays());
System.out.println("Hours: " + period.getHours());
System.out.println("Minutes: " + period.getMinutes());
output is
Weeks: 5
Days: 5
Hours: 8
Minutes: 15
works like a charm
instead of Weeks.weeksBetween you can use next solution (using PeriodType)
PeriodType periodType = PeriodType.standard().withMonthsRemoved();
Period period = new Period(new Date(2012, 11, 11, 12, 00, 00).getTime(), new Date(2012, 12, 16, 20, 15, 00).getTime(), periodType);
System.out.println(period.getWeeks());
output is
5