How to add N weeks to the current date in Kotlin

1 Answer

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

/**
 * Adds a specified number of weeks to the current system date.
 *
 * @param weeks The number of weeks to add (supports negative numbers to subtract).
 * @return LocalDate The resulting future date as an immutable object.
 */
fun addWeeksToCurrentDate(weeks: Long): LocalDate {
    // 1. Get the current date using the system clock in the default time zone
    val currentDate: LocalDate = LocalDate.now()
    
    // 2. Add the specified weeks using the built-in plusWeeks method.
    // This automatically handles month lengths, year rollovers, and leap years.
    return currentDate.plusWeeks(weeks)
}

fun main() {
    val weeksToAdd: Long = 4

    // Calculate the future date
    val futureDate: LocalDate = addWeeksToCurrentDate(weeksToAdd)

    // Format the date into standard ISO-8601 (YYYY-MM-DD)
    val formattedDate: String = futureDate.format(DateTimeFormatter.ISO_LOCAL_DATE)

    println("Adding $weeksToAdd weeks to today's date gives: $formattedDate")
}


/*
run:

Adding 4 weeks to today's date gives: 2026-12-06

*/

 



answered 18 hours ago by avibootz
...