Find out how many days passed from one date to another

Asked

Viewed 1,347 times

4

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

2 answers

11


To Date-Time API Java 8 greatly facilitated this type of operation.

For your specific problem we can avail ourselves of the units ChronoUnit. The method between does exactly what you’re wanting.

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

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);
  • 1

    Good. I forgot to say, for Java 5 or higher we have the library Joda-Time. With it the code shortens to Days.between(begin, end).getDays().

  • We can also use Timeunit to avoid manual conversions: TimeUnit.DAYS.convert(diferencaEmMilisegundos, TimeUnit.MILLISECONDS).

  • 1

    Joda-time proceeds! Now Timeunit only from Java 5, and Constant DAYS only from Java 6 :)

Browser other questions tagged

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