Calculating days between two dates with Java

To calculate the number of days between two dates in Java, you can use the Period class from the java.time package introduced in Java 8.

Here's an example of how to use Period to calculate the number of days between two dates:

import java.time.LocalDate;
import java.time.Period;

public class Main {
  public static void main(String[] args) {
    LocalDate start = LocalDate.of(2022, 1, 1);
    LocalDate end = LocalDate.of(2022, 1, 31);
    Period period = Period.between(start, end);
    int days = period.getDays();
    System.out.println(days);  // Outputs: 30
  }
}

Note that Period can also be used to calculate the number of months and years between two dates, in addition to days.

Period period = Period.between(start, end);
int years = period.getYears();
int months = period.getMonths();
int days = period.getDays();