datedatetimerustutcrust-chrono

rust chrono Utc add year, month using Add triats or better way


// Cargo.toml
chrono = { version = "0.4", features = ["serde", "rustc-serialize"] }
let mut date: DateTime<Utc> = DateTime::default();

date += Duration::years(1000); // no Duration::years()
date += Duration::months(1000); // no Duration::months()
date += Duration::days(1000); 
date += Duration::hours(1000); 
date += Duration::minutes(1000);
date += Duration::seconds(1000);
date = date.with_year(date.year() + 1000).unwrap(); // Ok
date = date.with_month(date.month() + 1000).unwrap(); // if date.with_month() parameter is over 12, panick

what is best way that calculate Utc in rust chrono??


Solution

  • Since a month can have anywhere from 28 to 31 days it's not a Duration, to still be able to work with them you can use the Months abstraction:

    use chrono::Months;
    date = date + Months::new(1000);