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.
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.
*You may also use the DATEDIFF function. COMPUTE month2 = DATEDIFF(date2,date1,"month"). EXE. COMPUTE year1 = (date2 - date1) / (60 * 60 * 24 * 365.24) .
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With