Calculating differences with chrono

Hello, I would like to ask if someone could give me an example of how to calculate difference with chrono years months and weeks from 2 timestamps with chrono?

What have you tried so far?

chrono does not have a timestamp struct, so I'm assuming you mean the difference between DateTime<_>?

It is surprisingly difficult to find the difference between two dates in terms of months and years, as months and years are not fixed units of time. Some months are longer than others, same goes for leap years. I'm not saying you need to, but if you also have to factor in different time zones and all the other weird stuff going on (daylight saving and leap seconds), you are in for a world of pain.

You can simply calculate the difference between two DateTime<_> objects as a Duration to get the difference between two dates in terms of days and weeks (and seconds, nanoseconds, etc), but not in terms of months and years:

use chrono::offset::{Utc, TimeZone};

fn main() {
    let a = Utc.with_ymd_and_hms(2023, 1, 1, 0, 0, 0).unwrap();
    let b = Utc.with_ymd_and_hms(2023, 2, 9, 0, 0, 0).unwrap();
    
    let diff = b - a;
    
    assert_eq!(diff.num_days(), 39);
    assert_eq!(diff.num_weeks(), 39 / 7);
}

Playground.

I think you have to implement the difference in terms of months and years between two Datelike structures yourself, according to your needs and your definition of that operation. Here is an example how I calculate the age of a person in the UTC time zone (so I guess closely related to what you expect as the difference in years between two dates) in one of my apps:

use chrono::{Datelike, NaiveDate};
use chrono::offset::Utc;

fn age<D: Datelike>(d: &D) -> i32 {
  let today = Utc::now();

  let mut age = today.year() - d.year();

  if today.ordinal() < d.ordinal() {
    age -= 1;
  }

  age
}

fn main() {
    let a = age(&NaiveDate::from_ymd_opt(1996, 4, 30).unwrap());
    assert!(a >= 26);

    let a = age(&NaiveDate::from_ymd_opt(2022, 1, 4).unwrap());
    assert!(a >= 1);
}
1 Like

very much nothing because i didn't see anything in the chrono with
months or years since every month have different days

2023-02-09 15:48 GMT+01:00, mdHMUpeyf8yluPfXI via The Rust Programming
Language Forum notifications@rust-lang.discoursemail.com:

Does this library meet your requirements?
https://crates.io/crates/date_component

yes it looks good thanks

do you think i did it wrong? i calculating difference from 2 local
timestamps but it looks inconsistent

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.