How to get the number of months between two dates in Rust

1 Answer

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

fn main() {
    // Define the variables as requested
    let startdate = NaiveDate::from_ymd_opt(2026, 1, 15).expect("Invalid start date");
    let enddate = NaiveDate::from_ymd_opt(2027, 7, 20).expect("Invalid end date");

    // Call the function to get the number of completed months
    let total_months = get_months_between(startdate, enddate);

    println!("Start Date:   {}", startdate.format("%Y-%m-%d"));
    println!("End Date:     {}", enddate.format("%Y-%m-%d"));
    println!("Total Months: {}", total_months);
}

/// Calculates the number of completed calendar months between two NaiveDates.
fn get_months_between(start_date: NaiveDate, end_date: NaiveDate) -> i32 {
    // Validate that the start date is not later than the end date
    assert!(start_date <= end_date, "Start date cannot be later than the end date.");

    // 1. Calculate the base month difference using years and months
    let years_diff = end_date.year() - start_date.year();
    let months_diff = end_date.month() as i32 - start_date.month() as i32;
    let mut total_months = (years_diff * 12) + months_diff;

    // 2. Adjust if the end day is earlier in the month than the start day
    // (meaning the final month hasn't fully elapsed yet)
    if end_date.day() < start_date.day() {
        total_months -= 1;
    }

    total_months
}


/*
run:

Start Date:   2026-01-15
End Date:     2027-07-20
Total Months: 18

*/

 



answered 3 days ago by avibootz
...