How to add N weeks to the current date in Rust

1 Answer

0 votes
use chrono::{DateTime, Utc, Duration};

/// Adds a specified number of weeks to the current UTC date and time.
///
/// # Arguments
/// * `weeks` - The number of weeks to add (supports negative numbers to subtract).
///
/// # Returns
/// * `DateTime<Utc>` - The resulting future date and time.
pub fn add_weeks_to_current_date(weeks: i64) -> DateTime<Utc> {
    // 1. Get the current date and time in UTC
    let current_time = Utc::now();

    // 2. Construct a Duration for the specified number of weeks.
    // Chrono's Duration::weeks handles the internal conversion to days/seconds safely.
    let duration = Duration::weeks(weeks);

    // 3. Add the duration to the current time 
    // (Rust operators are overloaded; this returns a brand-new DateTime instance).
    current_time + duration
}

fn main() {
    let weeks_to_add: i64 = 4;

    // Calculate the future date and time
    let future_date = add_weeks_to_current_date(weeks_to_add);

    // Format the output as YYYY-MM-DD using strftime-like formatting
    println!("Adding {} weeks to today gives: {}", weeks_to_add, future_date.format("%Y-%m-%d"));
}


/*
run:

Adding 4 weeks to today gives: 2026-12-06

*/

 



answered 22 hours ago by avibootz
...