Scala ChronoUnit.DAYS.between
Subtract the arrival date from the departure date to count nights booked.
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(arrival, LocalDate.parse("2024-03-01"))
Run these examples in Scala
Save one example at a time as Lesson.scala. Use Scala 2.13 on JDK 21.
scalac Lesson.scala
scala LessonCount nights in a leap-year hotel stay
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
object Lesson {
def main(args: Array[String]): Unit = {
val arrival = LocalDate.parse("2024-02-28")
println(ChronoUnit.DAYS.between(arrival, LocalDate.parse("2024-03-01")))
}
}
2
A guest arriving on February 28 and leaving on March 1 stays the nights of February 28 and February 29.
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.
Close a same-day hire
A visitor returns a borrowed projector on the day it was collected. Count the number of midnights from the start date up to the end date, using local dates.
What to watch for
The checkout date is excluded. For calendar dates, avoid using the length of a local daylight-saving day as a constant.