How to add N weeks to the current date in Scala

1 Answer

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

object DateModifier {

  /**
   * 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.
   */
  def 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.
    currentDate.plusWeeks(weeks)
  }

  def main(args: Array[String]): Unit = {
    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(s"Adding $weeksToAdd weeks to today's date gives: $formattedDate")
  }
}


/*
run:

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

*/

 



answered 19 hours ago by avibootz
...