【问题标题】:How do I convert from Local timezone to UTC in Rust如何在 Rust 中从本地时区转换为 UTC
【发布时间】:2020-12-30 04:51:20
【问题描述】:

我正在尝试将我的本地时间转换为 UTC,如下所示

fn main() {

    let nd_local = NaiveDate::from_ymd(2020,10,10).and_hms(10,10,10);
    let time_at_kolkata = Kolkata.from_local_datetime(&nd_local);


    println!("KOLKATA_TIME {:?}", time_at_kolkata);
    println!("UTC TIME {:?}", time_at_kolkata.naive_utc());

}

但它会出错

println!("UTC TIME {:?}", time_at_kolkata.naive_utc());
   |                                               ^^^^^^^^^ method not found in `LocalResult<DateTime<Tz>>`

我在这里尝试将其转换为naive_utc。 但通常如何将我的 Kolkata 日期时间转换为 DateTime&lt;Utc&gt; 实例?

【问题讨论】:

  • 您可以将您的uses 添加到代码中吗?

标签: rust chrono


【解决方案1】:

但它会出错

println!("UTC TIME {:?}", time_at_kolkata.naive_utc());
   |                                               ^^^^^^^^^ method not found in `LocalResult<DateTime<Tz>>`

查看错误信息。你期待的是DateTime,但它清楚地告诉你它有一个LocalResult&lt;Datetime&lt;Tz&gt;&gt;

这是因为from_local_datetime is faillible:

将本地 NaiveDateTime 转换为可识别时区的 DateTime如果可能

强调我的,some naive datetimes don't map any date in the timezone, and some are ambiguous(可以映射到时区中的多个日期)。你需要决定whether 以及你将如何处理这些情况。

除此之外,

但通常我如何将我的 Kolkata 日期时间转换为 DateTime&lt;Utc&gt; 实例?

如上所述,您目前没有“加尔各答日期时间”,因此您需要解决这个问题。我实际上不确定您为什么要通过NaiveDateTime 然后将其本地化,因为TimeZone has the ymd/and_hms builders。所以你应该可以直接询问“2020 年 10 月 10 日 10:10:10 in Kolkata timezone”:

Kolkata::ymd(2020, 10, 10).and_hms(10, 10, 10)

然后,您可以使用with_timezone 来“移动”日期时间。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-09-16
    • 1970-01-01
    • 2021-04-20
    • 2021-04-25
    • 1970-01-01
    • 2014-01-31
    • 1970-01-01
    • 2019-05-31
    相关资源
    最近更新 更多