How to calculate differences in a few months using Java’s joda API

I'm writing a program that should calculate the month between two given dates and return the value to the program For example, if I have to calculate the months between April 1 and June 30 (this is a quarter, three months), I use the following code:

DateTime start = new DateTime().withDate(2011,4,1);
    DateTime end = new DateTime().withDate(2011,6,30);

    Months mt = Months.monthsBetween(start,end);
    int monthDiff = mt.getMonths();

Using it, I still count "2" as months, but actually "3" months This is an example I want I only calculate the number of months (i.e. from the first month of the starting month of the last month of the ending month). I don't need additional analysis, such as days, weeks, hours, etc How?

Any help would be appreciated

Solution

DateTime start = new DateTime().withDate(2011,1);
DateTime start = new DateTime().withDate(2011,1);
DateTime end = new DateTime().withDate(2011,30);
Period p = new Period(start,end,PeriodType.months().withDaysRemoved());
int months = p.getMonths() + 1;

You need the withdaysremoved () section to make sure you add one to several months of work Otherwise, for example, April 15, 2011 and June 14, 2011 will still lead to the answer of 2

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>