[英]Idiomatic way to check if a chrono::DateTime<Utc> is within date and time range?
I am curious if there is an idiomatic way to check if a chrono::DateTime<Utc>
is within a time range.我很好奇是否有一种惯用的方法来检查
chrono::DateTime<Utc>
是否在一个时间范围内。 In my use case I just need to check if the DateTime
falls within the next half hour, from current time.在我的用例中,我只需要检查
DateTime
是否在当前时间的下半小时内。
This is what I put together so far.这是我到目前为止放在一起的。 Its using
timestamp()
attribute to get a raw (unix) timestamp I can work with.它使用
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
}
My test cases are something like this:我的测试用例是这样的:
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));
}
I am curious if there is a more idiomatic approach to achieve the same result.我很好奇是否有更惯用的方法来达到相同的结果。
If you convert everything to chrono::DateTime
and chrono::Duration
, things get a lot simpler:如果将所有内容都转换为
chrono::DateTime
和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() { /* ... */ }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.