How to convert days into human-readable years, months and days in Rust

2 Answers

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

struct YMD {
    years: i32,
    months: i32,
    days: i32,
}

fn split_days(total_days: i64) -> YMD {
    let start = NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
    let end = start + Duration::days(total_days);

    let mut years  = end.year()  - start.year();
    let mut months = end.month() as i32 - start.month() as i32;
    let mut days   = end.day() as i32   - start.day() as i32;

    // Normalize negative days
    if days < 0 {
        months -= 1;
        let prev_month = end.with_day(1).unwrap().pred_opt().unwrap();
        days += prev_month.day() as i32;
    }

    // Normalize negative months
    if months < 0 {
        months += 12;
        years -= 1;
    }

    YMD { years, months, days }
}

fn main() {
    let r = split_days(452);
    
    println!("{} years, {} months, {} days", r.years, r.months, r.days);
}




/*
run:

1 years, 2 months, 28 days

*/

 



answered Jan 1 by avibootz
0 votes
struct YMD {
    years: i32,
    months: i32,
    days: i32,
}

fn split_days(mut total_days: i32) -> YMD {
    let years = total_days / 365;
    total_days %= 365;

    let months = total_days / 30;
    total_days %= 30;

    let days = total_days;

    YMD { years, months, days }
}

fn main() {
    let r = split_days(452);
    
    println!("{} years, {} months, {} days", r.years, r.months, r.days);
}




/*
run:

1 years, 2 months, 27 days

*/

 



answered Jan 1 by avibootz

Related questions

...