How to check if a date is in the future with Rust

2 Answers

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

/// Checks if a given year, month, and day are strictly in the future compared to today.
/// Returns Some(true) if in the future, Some(false) otherwise, or None if the date is invalid.
fn is_date_in_future(year: i32, month: u32, day: u32) -> Option<bool> {
    // 1. Construct and validate the target date safely
    let target_date = NaiveDate::from_ymd_opt(year, month, day)?;

    // 2. Get today's date in UTC (ignoring time components for a clean calendar comparison)
    let today = Utc::now().date_naive();

    // 3. Compare dates directly using standard comparison operators
    Some(target_date > today)
}

fn main() {
    let test_year = 2035;
    let test_month = 6;
    let test_day = 15;

    println!("Checking date: {:04}-{:02}-{:02}", test_year, test_month, test_day);

    match is_date_in_future(test_year, test_month, test_day) {
        Some(true) => println!("Result: The date is in the FUTURE."),
        Some(false) => println!("Result: The date is NOT in the future."),
        None => println!("Error: Invalid calendar date provided."),
    }
}


/*
run:

  
Checking date: 2035-06-15
Result: The date is in the FUTURE.

*/

 



answered 2 hours ago by avibootz
0 votes
use time::{Date, Month, OffsetDateTime};

/// Checks if a date is in the future using the `time` crate.
fn is_date_in_future_time_crate(year: i32, month: Month, day: u8) -> Result<bool, &'static str> {
    // 1. Construct the target date
    let target_date = Date::from_calendar_date(year, month, day)
        .map_err(|_| "Invalid calendar date provided.")?;

    // 2. Get current UTC date
    let now = OffsetDateTime::now_utc();
    let today = now.date();

    // 3. Compare dates
    Ok(target_date > today)
}

fn main() {
    let test_year = 2035;
    let test_month = Month::June;
    let test_day = 15;

    println!("Checking date: {}-06-15", test_year);

    match is_date_in_future_time_crate(test_year, test_month, test_day) {
        Ok(true) => println!("Result: The date is in the FUTURE."),
        Ok(false) => println!("Result: The date is NOT in the future."),
        Err(e) => println!("Error: {}", e),
    }
}


/*
run:

  
Checking date: 2035-06-15
Result: The date is in the FUTURE.

*/

 



answered 2 hours ago by avibootz
...