With Java 8, you do not have to use an external library to reliably calculate the difference between two dates. Also, it is recommended that you do not use the java.util.Date
class in many cases.
To calculate the difference between months in a simple way, just do something like this:
//define datas
LocalDateTime dataCadastro = LocalDateTime.of(2015, 1, 1, 0, 0, 0);
LocalDateTime hoje = LocalDateTime.now();
//calcula diferença
long meses = dataCadastro.until(hoje, ChronoUnit.MONTHS);
It is worth noting that the difference will be only in the number of months, without considering the day. If the registration was done on the 31st of a given month, the next day the routine will indicate 1 month of difference. So it is important to describe in the system a business rule defining exactly what a difference from n months .
If you do not have Java 8, you also do not need a library to make that simple difference. You can use the java.util.Calendar
class:
//define datas
Calendar dataCadastro = Calendar.getInstance();
dataCadastro.set(2015, 1, 1);
Calendar hoje = Calendar.getInstance();
//calcula diferença
int meses = (hoje.get(Calendar.YEAR) * 12 + hoje.get(Calendar.MONTH))
- (dataCadastro.get(Calendar.YEAR) * 12 + dataCadastro.get(Calendar.MONTH));
The above method uses a simple technique that calculates the number of months that the dates contain, multiplying the year by 12 and adding the months, then makes the subtraction simple. This is a very common technique and works well when the goal is to disregard days and times, and I have used it frequently in accounting systems.
Finally, if you need to transform a Date
to Calendar
, just do:
calendar.setTime(date);