rustrust-chrono

How do I add a month to a Chrono NaiveDate?


I am trying to create a date picker and I need to navigate between months

let current = NaiveDate::parse_from_str("2020-10-15", "%Y-%m-%d").unwrap();

How can I generate the date 2020-11-15?


Solution

  • Here is my solution:

    use chrono::{ NaiveDate, Duration, Datelike};
    
    fn get_days_from_month(year: i32, month: u32) -> u32 {
        NaiveDate::from_ymd(
            match month {
                12 => year + 1,
                _ => year,
            },
            match month {
                12 => 1,
                _ => month + 1,
            },
            1,
        )
        .signed_duration_since(NaiveDate::from_ymd(year, month, 1))
        .num_days() as u32
    }
    
    fn add_months(date: NaiveDate, num_months: u32) -> NaiveDate {
        let mut month = date.month() + num_months;
        let year = date.year() + (month / 12) as i32;
        month = month % 12;
        let mut day = date.day();
        let max_days = get_days_from_month(year, month);
        day = if day > max_days { max_days } else { day };
        NaiveDate::from_ymd(year, month, day)
    }
    
    fn main() {
        let date = NaiveDate::parse_from_str("2020-10-31", "%Y-%m-%d").unwrap();
        let new_date = add_months(date, 4);
        println!("{:?}", new_date);
    }