Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
562 views
in Technique[技术] by (71.8m points)

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

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 number of months between 1 April and 30 June (which is a quarter, 3 months), and 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 this, I am still getting "2" as the number of months, whereas it is actually "3" months. This is an example of what I want. I am only calculating the number of months (i.e. from 1st of the start month t the last date of the end month) and I dont need additional analysis like days, weeks, hours, etc. How do I achieve this?

Any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...