If I have 2 Date type variables:
Date fecha1 = new SimpleDateFormat("dd/MM/yyyy").parse("01/05/2017");
Date fecha2 = new SimpleDateFormat("dd/MM/yyyy").parse("01/08/2018");
that the result gives me back 15 months of difference.
Is there any way to obtain it?
You can use
java.util.Calendar
First what we do is set 2 dates, one start and one end.
inicio
andfin
in this case.Then we calculate the difference in years between the two dates (
difA
). This in case the difference between months is greater than 12 we can calculate it.Once this is done we need to calculate the number of months between those years, for that we multiply 12 by the difference in years between the two dates and to this we add the number of the month of the end date and finally we subtract the number of the start month and we get the difference in months between the dates (
difM
).