Calculate months between two year-based dates using JodaTime

I use this code to calculate months between pastdate and currentdate input. He uses JodaTime

LocalDate date1 = new LocalDate(installmentStartDate2); LocalDate date2 = new LocalDate(new java.util.Date()); PeriodType monthDay = PeriodType.yearMonthDayTime(); Period difference = new Period(date1, date2, monthDay); int months = difference.getMonths(); return months + 1; 

Now when I enter January 1, 2013, I get 10 as an answer. But the problem is to get 10, even when I enter 1 jan 2012.

Thus, this means that when calculating it, it does not take into account the year.

What can I do to get the correct answer, i.e. 22 when I introduce Jan 1, 2012.

Can JodaTime do this? If yes? How? If not? Any other approach?

+6
source share
4 answers

Your code is almost right.

You can change:

 PeriodType monthDay = PeriodType.yearMonthDayTime(); 

to:

 PeriodType monthDay = PeriodType.months(); 

and it will also work.

+3
source

You ask for the difference in years, months, and days, so you return for 1 year, 10 months, and 29 days.

Just use:

 int months = Months.monthsBetween(date1, date2).getMonths(); 

Or, if you really want to use the new Period and maybe get the days, you can use:

 PeriodType monthDay = PeriodType.yearMonthDayTime().withYearsRemoved(); Period difference = new Period(date1, date2, monthDay); 

You can simply use PeriodType.months() , but if you are really only interested in months, I would use the first snippet above to do it all in one short different statement.

+19
source

Time in Jod is a good way to deal with this problem.

Create a Jod Date Object

 DateTime startDate = DateTime.parse("1970-01-01", DateTimeFormat.forPattern("yyyy-MM-dd")) DateTime endDate = DateTime.parse("2015-02-25", DateTimeFormat.forPattern("yyyy-MM-dd")) 

The difference between the two dates in days

 int days = Days.daysBetween(startDate, endDate).getDays() 

The difference between two dates in months

 int months = Months.monthsBetween(startDate.withDayOfMonth(1), endDate.withDayOfMonth(1)).getMonths() 

The difference between two dates in years

 int years = Years.yearsBetween(startDate, endDate).getYears(); 
+1
source

I suggest using this:

 ChronoUnit.MONTHS.between(earlierDate,date) 
0
source

Source: https://habr.com/ru/post/957014/


All Articles