I am curious if there is an idiomatic way to check if a chrono::DateTime<Utc>
is within a time range. In my use case I just need to check if the DateTime
falls within the next half hour, from current time.
This is what I put together so far. Its using timestamp()
attribute to get a raw (unix) timestamp I can work with.
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:
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() { /* ... */ }