[英]Right Period between two Java Dates
I need help to get the Period between two Java Dates. 我需要帮助来获取两个Java日期之间的期间。 I use JodaTime for the calculation but the result isn't correct. 我使用JodaTime进行计算,但结果不正确。
Start: 11.11.2012 12:00 开始:11.11.2012 12:00
End: 16.12.2012 20:15 结束于:16.12.2012 20:15
(German time standard) (德国时间标准)
Result musst be 5 weeks, 0 days, 8 hours and 15 minutes. 结果至少需要5周,0天,8小时和15分钟。
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. 并得到了5w 5d 8h 15m。
EDIT: 编辑:
Thanks for the help but i think i use the JodaTime Period wrong. 感谢您的帮助,但我认为我在JodaTime时期使用错误。 Off course is the output of 5w 5d 8h 15m right but what i want is more like this. 当然,5w 5d 8h 15m的输出正确,但是我想要的更像是这样。
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. 现在是我5周零0天的结果。 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
) 而不是Weeks.weeksBetween
您可以使用下一个解决方案(使用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
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. 期间将计算一个月而不是5个星期。 So we first count the weeks between the two dates, and use a Period for the remainder. 因此,我们首先计算两个日期之间的周数,然后使用“期间”作为余数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.