Calculate Number of Days Between Two Dates

Calculate Number of Days Between Two Dates

To calculate number of days between two dates, we can use Duration.between() method. In the code below, dates are passed as strings, like 2012-12-30.

import java.time.Duration
import java.time.LocalDate

fun daysBetweenDates(date1: String, date2: String): Int {
    return Math.abs(
        Duration.between(
            LocalDate.parse(date1).atStartOfDay(),
            LocalDate.parse(date2).atStartOfDay()
        ).toDays().toInt()
    )
}

The usage of atStartOfDay() is required, otherwise it fails with UnsupportedTemporalTypeException.

Exception in thread "main" java.time.temporal.UnsupportedTemporalTypeException: Unsupported unit: Seconds
	at java.time.LocalDate.until(LocalDate.java:1614)
	at java.time.Duration.between(Duration.java:475)
© 2021 VividCode