我很好奇是否有一种惯用的方法可以检查一个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));
}
我很好奇是否有更加惯用的方法来达到同样的结果。
.timestamp()
的方法实际上快了约两倍,假设我缓存Utc::now().timestamp()
的值而不是每次都计算它(对于另一个版本的Utc::now()
也是如此)。虽然我仍然喜欢使用chrono::Duration
的版本,因为我认为它总体上更符合习惯用法。 - rv.kvetch.timestamp()
的调用没有被优化掉,我会感到惊讶的。 - BallpointBen