【发布时间】:2020-11-27 16:57:29
【问题描述】:
我正在将 Rust 与 Chrono 库一起使用,并且需要在 UTC 时间下午 6 点找到上周二的 DateTime。
我有以下代码,它似乎可以工作,但似乎比应有的复杂。
use chrono::{DateTime, Utc, Duration, Datelike};
use chrono::prelude::*;
fn main() {
let now: DateTime<Utc> = Utc::now();
let n_date = Utc::now().date();
let dt = Utc.ymd(n_date.year(), n_date.month(), n_date.day()).and_hms(18, 0, 0);
let current_day = now.weekday().number_from_monday();
let target_dt = if current_day == 2 {
if dt > now {
dt
} else {
dt - Duration::days(7)
}
}
else if current_day > 2 {
dt - Duration::days((current_day - 2) as i64)
} else {
dt - Duration::days(6)
};
println!("{:?}", target_dt);
}
是否有更有效/更好的方法来查找前一周的特定日期时间? (在这种情况下,前一个星期二 18:00 UTC)。看看其他一些语言,只有一条线的解决方案,我觉得我一定遗漏了一些明显的东西。
根据下面的反馈,这里是更新的代码:
let now: DateTime<Utc> = Utc::now();
//use this to test specific dates / times
//let now : DateTime<Utc> = Utc.ymd(2020, 11, 24).and_hms(18, 0, 1);
let n_date = now.date();
//let n_date = Utc.ymd(2020, 11, 24).and_hms(17, 0, 0).date();
let dt = Utc.ymd(n_date.year(), n_date.month(), n_date.day()).and_hms(18, 0, 0);
let w_day = n_date.weekday();
let target_dt = if w_day == Weekday::Tue {
if now > dt {
dt
} else {
dt - Duration::days(7)
}
} else {
let c:i64 = ((w_day.num_days_from_sunday() + 4) % 7 + 1) as i64;
dt - Duration::days(c)
};
println!("{:?}", target_dt);
好的。在考虑了更多之后,我想出了一个更直接的方法,这可以证明我可以使用以前知道的重置数据/时间作为参考:
pub const WEEK_IN_SECONDS: i64 = 60 * 60 * 24 * 7;
pub fn get_last_reset() -> DateTime<Utc> {
//get a hardcoded past reset date / time
let past_reset : DateTime<Utc> = Utc.ymd(2020, 11, 10).and_hms(18, 0, 0);
let now: DateTime<Utc> = Utc::now();
//get total seconds between now and the past reset
//take the mod of that divided by a week in seconds
//subtract that amount from current date / time to find previous reset
now - Duration::seconds((now - past_reset).num_seconds() % WEEK_IN_SECONDS)
}
【问题讨论】:
-
if dt > now { dt }如果今天是周二早上/中午之后(小于 1800)那么今天返回 1800 吗?
标签: rust