简体   繁体   English

使用Java / Joda的日期之间的时间段

[英]Period between dates using Java/Joda

I have 2 joda dates as follows: 我有2个joda日期,如下所示:

org.joda.time.DateTime a;
org.joda.time.DateTime b;

I want the difference between the 2 dates in terms of Years, months and days (eg. 0 years, 2 months, 5 days). 我想要两个日期之间以年,月和天为单位的差异(例如0年,2个月,5天)。
I can use the org.joda.time.Days.daysBetween(a, b) or monthsBetween(a, b) or yearsBetween(a, b) to get the whole values of each respectively. 我可以使用org.joda.time.Days.daysBetween(a, b)monthsBetween(a, b)yearsBetween(a, b)来分别获取每个值的全部值。 Since a month does have number of fixed number of days, how can I calculate this? 由于一个月确实有固定的天数,该如何计算?

Eg. 例如。 If I get monthsbetween = 2 and daysbetween = 65 , how can I write this as "2 months and x days" 如果我得到daysbetween = 65 monthsbetween = 2monthsbetween = 2 daysbetween = 65daysbetween = 65 ,如何将其写为"2 months and x days"

Is there any other way to get this? 还有其他方法可以做到这一点吗?

Try this: 尝试这个:

Calendar ca = Calendar.getInstance();
ca.setTime(a);
Calendar cb = Calendar.getInstance();
cb.setTime(b);
System.out.printf("%d months and %d days"
    , ca.get(Calendar.MONTH) - cb.get(Calendar.MONTH)
    , ca.get(Calendar.DAY_OF_MONTH) - cb.get(Calendar.DAY_OF_MONTH));

Im not too familiar with Joda, but it looks like your best option is to divide the days left by 30.5, and then round it up back to a whole integer. 我对Joda不太熟悉,但是看来最好的选择是将剩余天数除以30.5,然后将其四舍五入为整数。 Like so: 像这样:

double daysDivided = daysbetween / 30.5;
int daysbetweenFixed = (int) daysDivided;

System.out.printf("%d months and %d days", monthsbetween, daysbetweenFixed);
//optional output ^

I'm sure you would know i chose 30.5 because it seems like the a good average month length, excluding February. 我确定您会选择30.5,因为这似乎是一个不错的平均月份长度,不包括2月。 Because there is no set length of a month this is the best we can do with only these integers. 因为没有设定一个月的长度,所以这是我们只能使用这些整数的最佳方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM