How to calculate difference ONLY in months using Java's Joda API

前端 未结 6 832
忘了有多久
忘了有多久 2020-12-17 21:32

I am writing a program that is supposed to just calculate the months between 2 given dates and return the value to the program. For instance, if I have to calculate the numb

相关标签:
6条回答
  • 2020-12-17 21:41

    Why do you expect the answer to be 3 months? The precise answer is two months and a little bit, which then results in the two months you are getting.

    If you want the number of months that are “touched” by this interval, this is a completely different question. Just add 1 to the result of the difference.

    0 讨论(0)
  • 2020-12-17 21:46
    DateTime start = new DateTime().withDate(2011, 4, 1);
            DateTime end = new DateTime().withDate(2011, 2, 1);
            Period p = new Period(start, end, PeriodType.months().withDaysRemoved());
            int months = p.getMonths();
            System.out.println(months);
    
    
    wrong output in this case
    
    0 讨论(0)
  • 2020-12-17 21:56
    DateTime start = new DateTime().withDate(2011, 4, 1);
    DateTime end = new DateTime().withDate(2011, 6, 30);
    Period p = new Period(start, end, PeriodType.months().withDaysRemoved());
    int months = p.getMonths() + 1;
    

    You need the withDaysRemoved() part to ensure that adding one to the number of months works. Otherwise two dates such as 2011-04-15 and 2011-06-14 would still result in the answer being 2

    0 讨论(0)
  • 2020-12-17 21:56

    Let y1 and m1 be the year and month of the start date, and y2 and m2 be the year and month of the end date. Then the number of months between start and end, including the months of the start and end dates is

    (y2 - y1) * 12 + (m2 - m1) + 1
    
    0 讨论(0)
  • 2020-12-17 22:02

    Joda algorithm counted correctly difference between this two dates. This pseudo-code will be the easiest way to explain how it works:

    // (1)
    monthsBetween(2011.6.14, 2011.4.15) = 1
    monthsBetween(2011.6.15, 2011.4.15) = 2
    // (2)
    monthsBetween(2011.6.30, 2011.4.1) = 2
    monthsBetween(2011.7.1,  2011.4.1) = 3
    

    To do what you want you need to "improve" joda algorithm:

    • Count distance between two dates (use normal monthsBetween)
    • If you have specific situation: the last day of month in one date and the 1st day of month in second date, add +1 to the final result.
    0 讨论(0)
  • 2020-12-17 22:03
    Months mt = Months.monthsBetween(
        start.monthOfYear().roundFloorCopy(), 
        end.monthOfYear().roundCeilingCopy()
    );
    
    0 讨论(0)
提交回复
热议问题