使用Chrono计算现在和下一个午夜之间的持续时间

csp*_*tta 3 rust rust-chrono

从现在到下一个午夜之间获得持续时间的惯用方法是什么?

我有这样的功能:

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??
}
Run Code Online (Sandbox Code Playgroud)

它应该是Duration1小时,因为下一个午夜是2017年12月9日星期六00:00:00 GMT-0300(-03)

Mat*_* M. 5

在搜索完文档后,我终于找到了缺失的链接:Date::and_hms.

所以,实际上,它很简单:

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);
}
Run Code Online (Sandbox Code Playgroud)

这个想法很简单:

  • 增加到DateTime明天,
  • 提取Date保留时区的部分,
  • 重建一个新的DateTime通过指定"00:00:00" Timeand_hms.

有一个panic!in and_hms,所以必须小心指定正确的时间.

  • @azzamsa:文档和游乐场不同意您的评估,请参阅 https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a84e6dfc4986df59342b5edec07485b1 和 https://docs.rs/chrono 的最新示例/0.4.19/chrono/naive/struct.NaiveDateTime.html#method.checked_add_signed (3认同)