我很好奇是否有一種慣用的方法來檢查 achrono::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));
}
我很好奇是否有更慣用的方法來實作相同的結果。
uj5u.com熱心網友回復:
如果將所有內容都轉換為chrono::DateTimeand 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() { /* ... */ }
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/459849.html
