只需减去两个日期:午夜和现在:
extern crate chrono;
use chrono::prelude::*;
use std::time;
fn duration_until_next_midnight() -> time::Duration {
let now = Local::now();
// change to next day and reset hour to 00:00
let midnight = (now + chrono::Duration::days(1))
.with_hour(0).unwrap()
.with_minute(0).unwrap()
.with_second(0).unwrap()
.with_nanosecond(0).unwrap();
println!("Duration between {:?} and {:?}:", now, midnight);
midnight.signed_duration_since(now).to_std().unwrap()
}
fn main() {
println!("{:?}", duration_until_next_midnight())
}
根据 Matthieu 的要求,您可以编写如下内容:
fn duration_until_next_midnight() -> Duration {
let now = Local::now();
// get the NaiveDate of tomorrow
let midnight_naivedate = (now + chrono::Duration::days(1)).naive_utc().date();
// create a NaiveDateTime from it
let midnight_naivedatetime = NaiveDateTime::new(midnight_naivedate, NaiveTime::from_hms(0, 0, 0));
// get the local DateTime of midnight
let midnight: DateTime<Local> = DateTime::from_utc(midnight_naivedatetime, *now.offset());
println!("Duration between {:?} and {:?}:", now, midnight);
midnight.signed_duration_since(now).to_std().unwrap()
}
但我不确定它是否更好。