Find out how many days have passed from one date to another

4

In a java program, where the person inserts the day first, then the month, then the year, how do I know how many days have passed from that date inserted until a later date that will also be reported by the person? For example: First reported date: 10/20/1990 Second reported date: 23 // 05/2005 How do I know the total number of days that have passed?

    
asked by anonymous 23.04.2015 / 22:11

2 answers

11

Java 8's Date-Time API made this type of operation much easier.

For your specific problem we can use ChronoUnit . The between does exactly what you're looking for.

LocalDate begin = LocalDate.of(1990, Month.OCTOBER, 20);
LocalDate end = LocalDate.of(2005, Month.MAY, 23);
long days = ChronoUnit.DAYS.between(begin, end); // 5329

Functional example in Ideone

    
23.04.2015 / 23:33
1

Solution from Java 1.4 focused on your problem:

String dataUm = "20/10/1990";
String dataDois = "23/05/2005";

SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd/MM/yyyy"); // dd/MM/yyyy é o formato brasileiro que você está usando, para mais formatos, veja o link de referência

Date dateUm = simpleDateFormat.parse(dataUm);
Date dateDois = simpleDateFormat.parse(dataDois);

long diferencaEmMilisegundos = dateDois.getTime() - dateUm.getTime();

/**
 * divide por 1000 para converter em segundos
 * divide por 60 para converter em minutos 
 * divide por 60 novamente para converter em horas
 * divide por 24 para converter em dias
 */
System.out.println(diferencaEmMilisegundos / 1000 / 60 / 60 / 24);
24.04.2015 / 00:26