Search code examples
rustrust-chrono

How to compute the duration between two chrono::DateTime?


I am using the chrono crate and want to compute the Duration between two DateTimes.

use chrono::Utc;
use chrono::offset::TimeZone;

let start_of_period = Utc.ymd(2020, 1, 1).and_hms(0, 0, 0);
let end_of_period = Utc.ymd(2021, 1, 1).and_hms(0, 0, 0);

// What should I enter here?
//
// The goal is to find a duration so that
// start_of_period + duration == end_of_period
// I expect duration to be of type std::time
let duration = ... 

let nb_of_days = duration.num_days();

Solution

  • DateTime implements Sub<DateTime>, so you can just subtract the most recent date from the first one:

    let duration = end_of_period - start_of_period;
    println!("num days = {}", duration.num_days());