I'm quite new to Rust and chrono library.
I checked the https://docs.rs/chrono/0.4.19/chrono/struct.Duration.html#method.num_weeks, but there's no num_years() or num_months() API in chrono::Duration.
Is there any work around solution for this ?
The crate chronoutil provides RelativeDuration which is "extending Chrono’s Duration to add months and years".
Example from docs.rs:
let one_day = RelativeDuration::days(1);
let one_month = RelativeDuration::months(1);
let delta = one_month + one_day;
let start = NaiveDate::from_ymd(2020, 1, 30);
assert_eq!(start + delta, NaiveDate::from_ymd(2020, 3, 1));
Note that one can not extract the duration in months or years from the duration alone. These properties can vary, depending on the point in time on the calendar that you are using.
For example, in the Gregorian calender, not all months are equally long (28 up to 31 days), it will depend on the starting date/time how many months fall within a duration.
The date_component crate takes this in to account. Given two dates, it calculates the months and years for you.
Example (from the documentation):
use chrono::prelude::*;
use date_component::date_component;
fn main() {
    let date1 = Utc.ymd(2015, 4, 20).and_hms(0, 0, 0);
    let date2 =  Utc.ymd(2015, 12, 19).and_hms(0, 0, 0);
    let date_interval = date_component::calculate(&date1, &date2);
    println!("{:?}", date_interval);
}
// DateComponent { year: 0, month: 7, week: 4, modulo_days: 1, day: 29, hour: 0, minute: 0, second: 0, interval_seconds: 20995200, interval_minutes: 349920, interval_hours: 5832, interval_days: 243, invert: false }
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With