Right Period between two Java Dates

穿精又带淫゛_ 提交于 2019-12-12 00:56:56

问题


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.


回答1:


    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



回答2:


For the output you want, I believe this is the solution :

    DateTime start = new DateTime(2012, 11, 11, 12, 0);
    DateTime end = new DateTime(2012, 12, 16, 20, 15);

    Weeks weeks = Weeks.weeksBetween(start, end);
    Period period = new Period(start.plus(weeks), end);
    System.out.println("Weeks : " + weeks.getWeeks());
    System.out.println("Days : " + period.getDays());
    System.out.println("Hours : " + period.getHours());
    System.out.println("Minutes : " + period.getMinutes());

A Period will count a month instead of 5 weeks. So we first count the weeks between the two dates, and use a Period for the remainder.



来源:https://stackoverflow.com/questions/13922496/right-period-between-two-java-dates

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!