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

标签 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??
}

Duration 应该是 1 小时,因为下一个午夜是 Sat Dec 09 2017 00:00:00 GMT-0300 (-03)

最佳答案

搜索文档后,我终于找到了丢失的链接: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);
}

这个想法很简单:

  • DateTime 增加到明天,
  • 提取保留时区的Date部分,
  • 通过使用 and_hms 指定“00:00:00”Time 来重建新的 DateTime

and_hms 中出现了panic!,因此必须小心指定正确的时间。

关于rust - 使用 Chrono 计算现在和下一个午夜之间的持续时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47708305/

相关文章:

rust - 如何在 Rocket.rs 的 url 中使用日期?

indexing - 遍历扁平化2D Vec列的更有效方法

rust-如何将这个宏与循环/递归结合起来?

rust - 意外的 T 与 &T 作为 Rust 中的类型参数

rust - 为什么 DateTime<Tz> 不能满足 serde::Serialize?

rust - 获取指定时区的当前时间

rust - 如何在WebAssembly中返回对嵌套Rust结构的引用?

rust - 为什么不能在同一结构中存储值和对该值的引用?

rust - 如何解析 RFC2822 中的日期,允许在字符串末尾使用时区?

datetime - 我如何使用 Chrono 从 NaiveDate 转到特定时区?