我有一个包含时间戳的结构。 为此,我正在使用 chrono library .获取时间戳的方式有两种:
- 通过
DateTime::parse_from_str
从字符串中解析出来结果是DateTime<FixedOffset>
- 当前时间,由
UTC::now
接收结果是DateTime<UTC>
.
有没有办法转换DateTime<UTC>
至 DateTime<FixedOffset>
?
最佳答案
我相信您正在寻找DateTime::with_timezone
:
use chrono::{DateTime, Local, TimeZone, Utc}; // 0.4.9
fn main() {
let now = Utc::now();
let then = Local
.datetime_from_str("Thu Jul 2 23:26:06 EDT 2015", "%a %h %d %H:%M:%S EDT %Y")
.unwrap();
println!("{}", now);
println!("{}", then);
let then_utc: DateTime<Utc> = then.with_timezone(&Utc);
println!("{}", then_utc);
}
我在 then_utc
上添加了一个冗余类型注释,以表明它是 UTC 格式的。此代码打印
2019-10-02 15:18:52.247884539 UTC
2015-07-02 23:26:06 +00:00
2015-07-02 23:26:06 UTC
关于rust - 如何将 DateTime<UTC> 转换为 DateTime<FixedOffset> 或反之?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31186864/