How to add N weeks to a given date in Swift

1 Answer

0 votes
import Foundation

/// Adds a specified number of weeks to a given Date.
///
/// - Parameters:
///   - baseDate: The original Date instance.
///   - weeks: The number of weeks to add (can also be negative to subtract).
///   - calendar: The calendar to use for date math (defaults to Calendar.current).
/// - Returns: A new Date with the added weeks, or nil if the calculation overflows or is invalid.
func addWeeksToDate(_ baseDate: Date, weeks: Int, calendar: Calendar = .current) -> Date? {
    // Multiplying weeks by 7 and adding days is a robust approach for pure calendar shifts.
    return calendar.date(byAdding: .day, value: weeks * 7, to: baseDate)
}

// Example usage
let calendar = Calendar.current
// Initialize a sample date: November 8, 2026
var components = DateComponents()
components.year = 2026
components.month = 11
components.day = 8

if let targetDate = calendar.date(from: components) {
    let weeksToAdd = 4

    // Perform the addition
    if let resultDate = addWeeksToDate(targetDate, weeks: weeksToAdd, calendar: calendar) {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd"
        
        print("Original date:        \(formatter.string(from: targetDate))")
        print("After adding \(weeksToAdd) weeks: \(formatter.string(from: resultDate))")
    } else {
        print("Error: Date calculation failed.")
    }
}


/*
run:

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

*/

 



answered 11 hours ago by avibootz
...