如何转换日期时间&lt;UTC&gt;到 DateTime<FixedOffset>或相反亦然? [英] How to convert DateTime&lt;UTC&gt; to DateTime&lt;FixedOffset&gt; or vice versa?

查看:83
本文介绍了如何转换日期时间&lt;UTC&gt;到 DateTime<FixedOffset>或相反亦然?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a struct that contains a timestamp. For that I am using the chrono library. There are two ways to get the timestamp:

  1. 通过 DateTime::parse_from_str 从字符串解析,结果为 DateTime
  2. 当前时间,由 UTC::now 接收,结果为 DateTime.
  1. Parsed from a string via DateTime::parse_from_str which results in a DateTime<FixedOffset>
  2. The current time, received by UTC::now which results in a DateTime<UTC>.

有没有办法将DateTime转换成DateTime?

推荐答案

我相信您正在寻找 DateTime::with_timezone:

I believe that you are looking for 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.此代码打印

I've added a redundant type annotation on then_utc to show it is in UTC. This code prints

2019-10-02 15:18:52.247884539 UTC
2015-07-02 23:26:06 +00:00
2015-07-02 23:26:06 UTC

这篇关于如何转换日期时间&lt;UTC&gt;到 DateTime<FixedOffset>或相反亦然?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆