I have start date and end date.
I need the number of months between this two dates in Java.
For example
- From date: 2009-01-29
- To date: 2009-02-02
It has one jan date and one Feb date.
It should return 2.
I have start date and end date.
I need the number of months between this two dates in Java.
For example
It has one jan date and one Feb date.
It should return 2.
Java 8 solution:
A full code snippet for finding the difference of months between two date is as follows:
Apart from using Joda time which seems to be the the favorite suggestion I'd offer the following snippet:
EDIT: Since Java 8, there is a more standard way of calculating same difference. See my alternative answer using JSR-310 api instead.
I had to write this implementation, becoz I had custom defined periods, which i had to look for within two dates. Here you can define you custom period and put the logic, for calculation.
Here TimePeriod is a POJO which has start, end, period start, period End
public class Monthly extends Period {
}
I would strongly recommend Joda-Time for this.
Note also Nick Holt's comments below re. daylight savings changes.