How to add N weeks to a given date in Rust

1 Answer

0 votes
use chrono::{NaiveDate, Duration};

/// Adds a specified number of weeks to a given NaiveDate safely.
/// 
/// @param base_date - The original NaiveDate.
/// @param weeks     - The number of weeks to add (can also be negative to subtract).
/// @return          - An Option<NaiveDate> returning Some(date) on success, or None on overflow.
pub fn add_weeks_to_date(base_date: NaiveDate, weeks: i64) -> Option<NaiveDate> {
    // chrono::Duration provides a built-in .weeks() constructor.
    // checked_add_signed safely handles calendar bounds, returning None instead of panicking on overflow.
    base_date.checked_add_signed(Duration::weeks(weeks))
}

fn main() {
    // Initialize a sample date: November 8, 2026 using the safe from_ymd_opt constructor
    let target_date = NaiveDate::from_ymd_opt(2026, 11, 8).expect("Invalid date provided");
    let weeks_to_add = 4;

    // Perform the addition with error handling for potential date overflows
    match add_weeks_to_date(target_date, weeks_to_add) {
        Some(result_date) => {
            println!("Original date:        {}", target_date);
            println!("After adding {} weeks: {}", weeks_to_add, result_date);
        }
        None => {
            eprintln!("Error: Date calculation resulted in an overflow or underflow.");
        }
    }
}


/*
run:

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

*/

 



answered 13 hours ago by avibootz
...