Calculate difference between dates

11

I need to calculate the difference between the date of registration and the current date, if it is greater than 6 months, return Boolean. I am registering the bank on the date of registration as follows:

public static final String DATE_FORMAT_NOW = "dd/MM/yyyy";

public static String date() 
    {
        Calendar cal = Calendar.getInstance();
        SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW);
        return sdf.format(cal.getTime());

    }

And I set this date function for the bank, now I need to make the difference between it and the current one.

    
asked by anonymous 15.11.2015 / 16:08

2 answers

9

Use the Joda-time library to make your life easier: Link

This library makes many things easier when dealing with dates, and should be the best way to work with it in java. To do what you want you can try this:

Period period = new Period(data1, data2);
period.getMonths(); // vai retornar a diferença de meses entre as duas datas
    
16.11.2015 / 04:46
13

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 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);
    
16.11.2015 / 08:49