如何将DateTime <UTC>转换为DateTime <FixedOffset>,反之亦然?

bus*_*ter 3 rust

我有一个包含时间戳的结构。为此,我正在使用chrono库。有两种获取时间戳的方法:

  1. 从字符串中解析出来DateTime::parse_from_str,结果是DateTime<FixedOffset>
  2. 接收到的当前时间,UTC::now结果为DateTime<UTC>

有没有办法转换DateTime<UTC>DateTime<FixedOffset>

She*_*ter 6

我相信您正在寻找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);
}
Run Code Online (Sandbox Code Playgroud)

我添加了一个多余的类型注释,then_utc以显示它在UTC中。此代码打印

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);
}
Run Code Online (Sandbox Code Playgroud)