NOTE THIS IS NOT A DUPLICATE OF EITHER OF THE FOLLOWING
I have two dates:
"2016-08-31"
"2016-11-30"
Its 91 days duration between the above two dates, I expected my code to return 3 months duration, but the below methods only returned 2 months. Does anyone have a better suggestion? Or do you guys think this is a bug in Java 8? 91 days the duration only return 2 months.
Thank you very much for the help.
Method 1:
Period diff = Period.between(LocalDate.parse("2016-08-31"), LocalDate.parse("2016-11-30"));
Method 2:
long daysBetween = ChronoUnit.MONTHS.between(LocalDate.parse("2016-08-31"), LocalDate.parse("2016-11-30"));
Method 3:
I tried to use Joda library instead of Java 8 APIs, it works. it loos will return 3, It looks like Java duration months calculation also used days value. But in my case, i cannot use the Joda at my project. So still looking for other solutions.
LocalDate dateBefore= LocalDate.parse("2016-08-31"); LocalDate dateAfter = LocalDate.parse("2016-11-30"); int months = Months.monthsBetween(dateBefore, dateAfter).getMonths(); System.out.println(months);
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.
Using JodaTime, you can get the difference between two dates in Java using the following code: Days d = Days. daysBetween(startDate, endDate). getDays();
Method 1: Period diff = Period. between(LocalDate. parse("2016-08-31"), LocalDate.
Since you don't care about the days in your case. You only want the number of month between two dates, use the documentation of the period to adapt the dates, it used the days as explain by Jacob
. Simply set the days of both instance to the same value (the first day of the month)
Period diff = Period.between( LocalDate.parse("2016-08-31").withDayOfMonth(1), LocalDate.parse("2016-11-30").withDayOfMonth(1)); System.out.println(diff); //P3M
Same with the other solution :
long monthsBetween = ChronoUnit.MONTHS.between( LocalDate.parse("2016-08-31").withDayOfMonth(1), LocalDate.parse("2016-11-30").withDayOfMonth(1)); System.out.println(monthsBetween); //3
Edit from @Olivier Grégoire comment:
Instead of using a LocalDate
and set the day to the first of the month, we can use YearMonth
that doesn't use the unit of days.
long monthsBetween = ChronoUnit.MONTHS.between( YearMonth.from(LocalDate.parse("2016-08-31")), YearMonth.from(LocalDate.parse("2016-11-30")) ) System.out.println(monthsBetween); //3
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