How to add N weeks to a given date in Kotlin

1 Answer

0 votes
import java.time.LocalDate
import java.time.format.DateTimeFormatter

/**
 * Adds a specified number of weeks to a given LocalDate.
 * 
 * @param baseDate The original LocalDate.
 * @param weeks    The number of weeks to add (can also be negative to subtract).
 * @return         A new LocalDate with the added weeks.
 */
fun addWeeksToDate(baseDate: LocalDate, weeks: Int): LocalDate {
    // plusWeeks() safely manages month and year boundaries, plus leap years.
    // Note: plusWeeks expects a Long, so we convert the Int weeks parameter.
    return baseDate.plusWeeks(weeks.toLong())
}

fun main() {
    // Initialize a sample date: November 8, 2026
    val targetDate = LocalDate.of(2026, 11, 8)
    val weeksToAdd = 4

    // Perform the addition
    val resultDate = addWeeksToDate(targetDate, weeksToAdd)

    // Format and display the results
    val formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd")
    println("Original date:        ${targetDate.format(formatter)}")
    println("After adding $weeksToAdd weeks: ${resultDate.format(formatter)}")
}


/*
run:

Original date:        2026-11-08
After adding 4 weeks: 2026-12-06

*/

 



answered 13 hours ago by avibootz
...