Calculate difference between dates

Asked

Viewed 16,185 times

12

I need to calculate the difference between the registration date and the current date, if it is greater than 6 months, return boolean. I am registering at the bank the registration date 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 play this date function for the bank, now I need to make the difference between it and the current.

  • 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?

3 answers

15

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);
  • Very good reply @utluiz, I didn’t know this, as for java 8, thank you! The good thing about Joda-Time, is all the extra features that it brings of bonus and of an easy way to do. But if he needs something specific only, that would be a solution.

13


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

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

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

0

public static void main(String[] args) {


    Data(28,2,2000,1,3,2008);

}

public static void Data (int dia1,int mes1,int ano1,int dia2,int mes2,int ano2){    

    int mes []= {31,0,31,30,31,30,31,31,30,31,30,31};       
    int dias = 0, meses = 0, anos = 0;  
    String temp = Integer.toString(ano1);

    if(temp.charAt(temp.length() - 1) == '0' && temp.charAt(temp.length() - 2) == '0') {             
        if(ano1 % 400 == 0) {
            mes[1] = 29;
        }else {
            mes[1] = 28;
        }       
    }else if(ano1 % 4 == 0) {
        mes[1] = 29;
    }else {
        mes[1] = 28;
    }       

    anos = ano2 - ano1;

    if(mes2 > mes1 || mes1 == mes2) {
        meses = mes2 - mes1;
    }else {
        meses = 12 - (mes1 - mes2);
        anos -= 1;
    }

    if(dia2 > dia1 || dia1 == dia2) {
        dias = dia2 - dia1;
    }else {
        dias = (mes[mes1 - 1] - dia1) + dia2;
        meses -= 1;
    }

    System.out.printf("* Diferença em dias/meses/anos:\n\n-> %d dia(s) / %d mes(es) / %d ano(s) .\n\n",dias,meses,anos);    

}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.