Search code examples
rustrust-chrono

Calculate the duration between now and the next midnight using Chrono


What is the idiomatic way to get the duration between now and the next midnight?

I have a function like this:

extern crate chrono;

use chrono::prelude::*;
use time;

fn duration_until_next_midnight() -> time::Duration {
    let now = Local::now(); // Fri Dec 08 2017 23:00:00 GMT-0300 (-03)
    // ... how to continue??
}

It should make a Duration with 1 hour, since the next midnight is Sat Dec 09 2017 00:00:00 GMT-0300 (-03)


Solution

  • After scouring the docs, I finally found the missing link: Date::and_hms.

    So, actually, it's as easy as:

    fn main() {
        let now = Local::now();
    
        let tomorrow_midnight = (now + Duration::days(1)).date().and_hms(0, 0, 0);
    
        let duration = tomorrow_midnight.signed_duration_since(now).to_std().unwrap();
    
        println!("Duration between {:?} and {:?}: {:?}", now, tomorrow_midnight, duration);
    }
    

    The idea is simple:

    • increase the DateTime to tomorrow,
    • extract the Date part, which keeps the timezone,
    • reconstructs a new DateTime by specifying a "00:00:00" Time with and_hms.

    There's a panic! in and_hms, so one has to be careful to specify a correct time.