How to add N weeks to a given date in Java

1 Answer

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

public class 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.
     */
    public static LocalDate addWeeksToDate(LocalDate baseDate, int weeks) {
        if (baseDate == null) {
            throw new IllegalArgumentException("Base date cannot be null.");
        }
        
        // plusWeeks() safely manages month and year boundaries, plus leap years.
        return baseDate.plusWeeks(weeks);
    }

    public static void main(String[] args) {
        // Initialize a sample date: November 8, 2026
        LocalDate targetDate = LocalDate.of(2026, 11, 8);
        int weeksToAdd = 4;

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

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


/*
run:

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

*/

 



answered 20 hours ago by avibootz
...