检查 chrono::DateTime 是否在日期和时间范围内的惯用方法?

2023-12-23

我很好奇是否有一种惯用的方法来检查是否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));
}

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


如果你将所有内容都转换为chrono::DateTime and chrono::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() { /* ... */ }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

检查 chrono::DateTime 是否在日期和时间范围内的惯用方法? 的相关文章

随机推荐