Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does rust chrono Duration get number of years or months?

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 ?

like image 654
linrongbin Avatar asked Oct 31 '25 22:10

linrongbin


1 Answers

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 }
like image 155
Code4R7 Avatar answered Nov 03 '25 13:11

Code4R7