rust里的时间控制
rust其实没有自带的time包,需要引入第三方,这里是0.3最新版本描述
首先,在Cargo.toml里加入
time = { version = "0.3", features=["parsing", "formatting", "macros", "local-offset"]}
- parsing和formatting是用来格式化的
- local-offset是用来获取当前时间
然后:
创建日期
let date = Date::from_calendar_date(2024, Month::July, 31).unwrap();
结果
2024-07-31
创建时间
let time = Time::from_hms(14, 30, 0).unwrap();
结果
14:30:00.0
创建完整的 DateTime
let datetime = PrimitiveDateTime::new(date, time);
结果
2024-07-31 14:30:00.0
日期时间运算
let later = datetime + Duration::days(7);
let earlier = datetime - Duration::hours(12);
let diff = later - earlier;
结果
later 2024-08-07 14:30:00.0
earlier 2024-07-31 2:30:00.0
diff 648000
时间间隔 Duration
let ten_minutes = Duration::minutes(10);
let gigasecond = Duration::seconds(1_000_000_000);
结果
10 分钟: Duration { seconds: 600, nanoseconds: 0 }
10 亿秒: Duration { seconds: 1000000000, nanoseconds: 0 }
当前时间(本地 / UTC)
let now = OffsetDateTime::now_local().unwrap(); // 当前本地时间
let utc_now = OffsetDateTime::now_utc(); // 当前 UTC 时间
let time_only = now.time(); // 得到 time::Time 类型
结果
当前时间: 2025-07-31 21:20:34.9443346 +08:00:00
当前 UTC 时间: 2025-07-31 13:20:34.9443671 +00:00:00
现在的时间: 21:20:34.9443346
从字符串转行
let date_str = "2025-07-31 14:30:00";
let datetime = PrimitiveDateTime::parse(
date_str,
&time::macros::format_description!("[year]-[month]-[day] [hour]:[minute]:[second]"),
)
.unwrap();
结果
2025-07-31 14:30:00.0
转化成字符串
let datetime_str = datetime
.format(&time::macros::format_description!(
"[year]-[month]-[day] [hour]:[minute]:[second]"
))
.unwrap();
结果
"2025-07-31 14:30:00"
浙公网安备 33010602011771号