How to get the number of months between two dates in Kotlin

1 Answer

0 votes
import java.time.LocalDate

fun main() {
    // Define the variables as requested
    val startdate: LocalDate = LocalDate.of(2026, 1, 15)
    val enddate: LocalDate = LocalDate.of(2027, 7, 20)

    // Call the function to get the number of completed months
    val totalMonths = getMonthsBetween(startdate, enddate)

    println("Start Date:   $startdate")
    println("End Date:     $enddate")
    println("Total Months: $totalMonths")
}

/**
 * Calculates the number of completed calendar months between two LocalDates.
 *
 * @param startDate The starting LocalDate.
 * @param endDate The ending LocalDate.
 * @return The number of full months between the dates.
 */
fun getMonthsBetween(startDate: LocalDate, endDate: LocalDate): Int {
    // Validate that the start date is not later than the end date
    require(!startDate.isAfter(endDate)) { "Start date cannot be later than the end date." }

    // 1. Calculate the base month difference using years and months
    val yearsDiff = endDate.year - startDate.year
    val monthsDiff = endDate.monthValue - startDate.monthValue
    var totalMonths = (yearsDiff * 12) + monthsDiff

    // 2. Adjust if the end day is earlier in the month than the start day
    // (meaning the final month hasn't fully elapsed yet)
    if (endDate.dayOfMonth < startDate.dayOfMonth) {
        totalMonths -= 1
    }

    return totalMonths
}


/*
run:

Start Date:   2026-01-15
End Date:     2027-07-20
Total Months: 18

*/

 



answered 3 days ago by avibootz
...