Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 871
Abhay Bhargav Avatar asked Sep 18 '11 09:09

Abhay Bhargav


People also ask

How to find difference in months between two dates in Java?

Once you have the LocalDate, you can use Months. monthsBetween() and Years. yearsBetween() method to calcualte the number of months and years between two dates in Java. LocalDate jamesBirthDay = new LocalDate(1955, 5, 19); LocalDate now = new LocalDate(2015, 7, 30); int monthsBetween = Months.

How do you calculate the number of months in difference between date1 and date2?

*You may also use the DATEDIFF function. COMPUTE month2 = DATEDIFF(date2,date1,"month"). EXE. COMPUTE year1 = (date2 - date1) / (60 * 60 * 24 * 365.24) .

How to find difference in dates in Java?

getTime() – d1. getTime(). Use date-time mathematical formula to find the difference between two dates. It returns the years, days, hours, minutes, and seconds between the two specifies dates.

How to find the number of days difference between two dates in Java?

The Period class has a between() method - just as the previously discussed ChronoUnit . This method takes in two LocalDate objects, one representing the starting date, and the second being the end date. It returns a Period consisting of the number of years, months, and days between two dates.


1 Answers

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

like image 120
Brian Roach Avatar answered Oct 04 '22 18:10

Brian Roach