Appearance
Calculating days between two dates with Java
To calculate the total number of days between two dates in Java, you can use the ChronoUnit class from the java.time.temporal package introduced in Java 8.
Here's an example of how to use ChronoUnit to calculate the total days between two dates:
java
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) {
LocalDate start = LocalDate.of(2022, 1, 1);
LocalDate end = LocalDate.of(2022, 1, 31);
long days = ChronoUnit.DAYS.between(start, end);
System.out.println(days); // Outputs: 30
}
}Note that Period is typically used to calculate a human-readable difference in years, months, and days. Unlike ChronoUnit, Period.between(start, end).getDays() only returns the days component of the period (0–31), not the total elapsed days.
java
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, 3, 15);
Period period = Period.between(start, end);
System.out.println(period.getYears() + " years, " + period.getMonths() + " months, " + period.getDays() + " days");
}
}