如何以惯用方式检查 chrono::DateTime<Utc> 是否在日期和时间范围内?

3

我很好奇是否有一种惯用的方法可以检查一个chrono::DateTime<Utc>是否在一个时间范围内。 在我的使用场景中,我只需要检查DateTime是否在当前时间之后的下半小时内。

目前,我已经组合了以下代码。它使用timestamp()属性来获取我可以处理的原始(unix)时间戳。

use chrono::prelude::*;
use chrono::Duration;

#[inline(always)]
pub fn in_next_half_hour(input_dt: DateTime<Utc>) -> bool {
    in_future_range(input_dt, 30 * 60)
}

/// Check if a `DateTime` occurs within the following X seconds from now.
pub fn in_future_range(input_dt: DateTime<Utc>, range_seconds: i64) -> bool {
    let utc_now_ts = Utc::now().timestamp();
    let input_ts = input_dt.timestamp();

    let within_range = input_ts > utc_now_ts && input_ts <= utc_now_ts + range_seconds;

    within_range
}

我的测试案例大致如下:

fn main() {
    let utc_now = Utc::now();

    let input_dt = utc_now - Duration::minutes(15);
    assert_eq!(false, in_next_half_hour(input_dt));

    let input_dt = utc_now + Duration::minutes(15);
    assert_eq!(true, in_next_half_hour(input_dt));

    let input_dt = utc_now + Duration::minutes(25);
    assert_eq!(true, in_next_half_hour(input_dt));

    let input_dt = utc_now + Duration::minutes(35);
    assert_eq!(false, in_next_half_hour(input_dt));

    let input_dt = utc_now - Duration::days(2);
    assert_eq!(false, in_next_half_hour(input_dt));

    let input_dt = utc_now + Duration::days(3);
    assert_eq!(false, in_next_half_hour(input_dt));
}

我很好奇是否有更加惯用的方法来达到同样的结果。

1个回答

5
如果你把所有东西都转换成chrono::DateTimechrono::Duration,事情就会变得更简单:
use chrono::prelude::*;
use chrono::Duration;

#[inline(always)]
pub fn in_next_half_hour(input_dt: DateTime<Utc>) -> bool {
    in_future_range(input_dt, Duration::minutes(30))
}

/// Check if a `DateTime` occurs within the following X seconds from now.
pub fn in_future_range(input_dt: DateTime<Utc>, range_dur: Duration) -> bool {
    let utc_now_dt = Utc::now();
    let within_range = utc_now_dt < input_dt && input_dt <= utc_now_dt + range_dur;
    within_range
}

fn main() { /* ... */ }

是的,这正是我想要转换的方法。有趣的是,我计时了一下,使用 .timestamp() 的方法实际上快了约两倍,假设我缓存 Utc::now().timestamp() 的值而不是每次都计算它(对于另一个版本的 Utc::now() 也是如此)。虽然我仍然喜欢使用 chrono::Duration 的版本,因为我认为它总体上更符合习惯用法。 - rv.kvetch
@rv.kvetch 是在调试版还是发布版中?如果两个对 .timestamp() 的调用没有被优化掉,我会感到惊讶的。 - BallpointBen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接