不确定我是否遗漏了某些东西,或者 chrono 同时扩展了它的功能集,但是它的 2021 年,至少从 chrono 0.4.0 开始,似乎有一种更清洁的方法来做到这一点:
https://docs.rs/chrono/0.4.19/chrono/#conversion-from-and-to-epoch-timestamps
use chrono::{DateTime, TimeZone, Utc};
// Construct a datetime from epoch:
let dt = Utc.timestamp(1_500_000_000, 0);
assert_eq!(dt.to_rfc2822(), "Fri, 14 Jul 2017 02:40:00 +0000");
// Get epoch value from a datetime:
let dt = DateTime::parse_from_rfc2822("Fri, 14 Jul 2017 02:40:00 +0000").unwrap();
assert_eq!(dt.timestamp(), 1_500_000_000);
所以你的完整转换应该是这样的:
extern crate chrono;
use chrono::*;
fn main() {
let start_date = chrono::Utc.ymd(2020, 1, 1).and_hms(0, 0, 0);
let ts = start_date.timestamp();
println!("{}", &ts);
let end_date = Utc.timestamp(ts, 0);
assert_eq!(end_date, start_date);
}