How to add N weeks to a given date in Scala

1 Answer

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

object DateAdditionExample {

  /** 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.
    */
  def addWeeksToDate(baseDate: LocalDate, weeks: Int): LocalDate = {
    require(baseDate != null, "Base date cannot be null.")
    
    // plusWeeks() safely manages month and year boundaries, plus leap years.
    baseDate.plusWeeks(weeks)
  }

  def main(args: Array[String]): Unit = {
    // 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(s"Original date:        ${targetDate.format(formatter)}")
    println(s"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
...