简体   繁体   English

两个月的Joda日期时间与剩余天数之间的差异

[英]Difference Between Two Joda DateTime In Months and Left Over Days

I have a requirement to get the amount of months between two DateTime objects and then get the number of days left over. 我需要获取两个DateTime对象之间的月数,然后获取剩余的天数。

Here is how I get the months between: 这是我得到两个月之间的时间的方法:

Months monthsBetween = Months.monthsBetween(dateOfBirth,endDate);

I am unsure how to then find out how many days are left over into the next month. 我不确定如何确定下个月还剩下多少天。 I have tried the following: 我尝试了以下方法:

int offset = Days.daysBetween(dateOfBirth,endDate)
              .minus(monthsBetween.get(DurationFieldType.days())).getDays();

But this does not have the desired effect. 但这并没有达到预期的效果。

Use a org.joda.time.Period : 使用org.joda.time.Period

// fields used by the period - use only months and days
PeriodType fields = PeriodType.forFields(new DurationFieldType[] {
        DurationFieldType.months(), DurationFieldType.days()
    });
Period period = new Period(dateOfBirth, endDate)
    // normalize to months and days
    .normalizedStandard(fields);

The normalization is needed because the period usually creates things like "1 month, 2 weeks and 3 days", and the normalization converts it to "1 month and 17 days". 需要进行归一化,因为该期间通常会创建诸如“ 1个月,2周和3天”之类的信息,并且归一化将其转换为“ 1个月和17天”。 Using the specific DurationFieldType 's above also makes it convert years to months automatically. 使用上面的特定DurationFieldType ,还可以自动将年份转换为月份。

Then you can get the number of months and days: 然后,您可以获得月数和天数:

int months = period.getMonths();
int days = period.getDays();

Another detail is that when using DateTime objects, the Period will also consider the time (hour, minute, secs) to know if a day has passed. 另一个细节是,在使用DateTime对象时, Period还将考虑知道一天是否过去的时间(小时,分钟,秒)。

If you want to ignore the time and consider only the date (day, month and year), don't forget to convert them to LocalDate : 如果您想忽略时间而只考虑日期(日,月和年),请不要忘记将它们转换为LocalDate

// convert DateTime to LocalDate, so time is ignored
Period period = new Period(dateOfBirth.toLocalDate(), endDate.toLocalDate())
    // normalize to months and days
    .normalizedStandard(fields);

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

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