How to count days between two dates in Java

Java 8Object Oriented ProgrammingProgramming

Let us first set two dates:

LocalDate date1 = LocalDate.of(2019, 4, 16);
LocalDate date2 = date1.with(Month.MAY).withDayOfMonth(04);

Now, count the dates between both the above dates using between():

int numDays = Period.between(date1, date2).getDays();

Example

import java.time.LocalDate;
import java.time.Month;
import java.time.Period;
public class Demo {
   public static void main(String[] argv) {
      LocalDate date1 = LocalDate.of(2019, 4, 16);
      LocalDate date2 = date1.with(Month.MAY).withDayOfMonth(04);
      int numDays = Period.between(date1, date2).getDays();
      System.out.println("Number of days between two dates = "+numDays);
   }
}

Output

Number of days between two dates = 18
raja
Published on 24-Apr-2019 12:08:12
Advertisements