Erik
Erik

Reputation: 909

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();

Upvotes: 10

Views: 4360

Answers (2)

mgostIH
mgostIH

Reputation: 466

Seeing the docs of Utc: https://docs.rs/chrono/0.4.11/chrono/offset/struct.Utc.html

By calling either the method .now (or .today) you get back a struct that implements Sub<Date<Tz>> for Date<Tz>, from source you can see it is returning an OldDuration, which is just a type alias around Duration.

Finally, you can use the Duration with the other types implementing Add for it, like DateTime.

So the code should look like this:

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);

let duration = end_of_period.now() - start_of_period.now();

Upvotes: 4

Peter Hall
Peter Hall

Reputation: 58835

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());

Upvotes: 12

Related Questions