Java ChronoUnit.DAYS.between
Count the days from check-in to check-out to get the number of nights. The check-out date marks the end of the stay.
A simple example
ChronoUnit.DAYS.between
- Start with Jan 1 and Jan 3 of the same year
- Do this Count elapsed days
- Result 2 days
Syntax
ChronoUnit.DAYS.between(checkIn, checkOut)
Run these examples in Java
Save one example at a time as Main.java. Use JDK 21.
java Main.javaBook across a leap day
A reservation spans the end of February in a leap year. The booking system must use actual calendar days so that the extra day appears in the schedule or stay length.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
public class Main {
public static void main(String[] args) throws Exception {
LocalDate checkIn = LocalDate.of(2024, 2, 28);
LocalDate checkOut = LocalDate.of(2024, 3, 1);
System.out.println(ChronoUnit.DAYS.between(checkIn, checkOut) + " nights");
}
}
2 nights
The guest sleeps at the hotel on February 28 and February 29. March 1 is the check-out day.
Count overnight stays for a school trip
A school group checks into a hostel on Friday and leaves on Monday morning. The teacher needs the number of nights to put on the booking form, including the Sunday night before checkout.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
class Main {
public static void main(String[] args) throws Exception {
var arrival = LocalDate.of(2026, 6, 12);
var departure = LocalDate.of(2026, 6, 15);
System.out.println(ChronoUnit.DAYS.between(arrival, departure) + " nights");
}
}
3 nights
Subtracting the Friday check-in date from the Monday checkout date counts three overnight stays. Checkout day does not add another night.
Count a winter cabin stay
A family arrives on December 30 and leaves on January 2. Count the number of midnights from the start date up to the end date, using local dates.
What to watch for
A reversed range gives a negative result. Validate the date order when accepting a booking.