With Java 8 it is not necessary to use an external library to calculate the difference between two dates reliably. Also, it is recommended not to use the class java.util.Date
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 made on the 31st of a given month, on the following day the routine will indicate 1 month difference. So it is important to describe in the system a business rule defining exactly what a difference of n months.
If you don’t have Java 8, you also don’t need a library to make this simple difference. You can use the class java.util.Calendar
:
//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 the dates contain, multiplying the year by 12 and summing up the months, then subtracts simply. This is a very common technique and works well when the goal is to disregard days and hours, and I used it frequently in accounting systems.
Finally, if you need to turn one Date
in Calendar
, just do:
calendar.setTime(date);
Where do you want to do it? In a query? Or do you want to calculate it in the results of a query, manipulating it directly in Java? What did you try?
– Vinícius Gobbo A. de Oliveira