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

前端 未结 6 836
忘了有多久
忘了有多久 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条回答
  •  萌比男神i
    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.

提交回复
热议问题