简体   繁体   English

如何在 Rust 中从本地时区转换为 UTC

[英]How do I convert from Local timezone to UTC in Rust

I am trying to convert my local time to UTC as below我正在尝试将我的本地时间转换为 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());

}

But it errors out as但它错误为

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

Here I am trying to convert it to naive_utc .在这里,我试图将其转换为naive_utc But generally how do I convert my Kolkata datetime to a DateTime<Utc> instance?但通常如何将我的Kolkata日期时间转换为DateTime<Utc>实例?

But it errors out as但它错误为

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

Look at the error message.查看错误消息。 You're expecting a DateTime but it clearly tells you that it has a LocalResult<Datetime<Tz>> .你期待一个DateTime但它清楚地告诉你它有一个LocalResult<Datetime<Tz>>

This is because from_local_datetime is faillible :这是因为from_local_datetime是 faillible

Converts the local NaiveDateTime to the timezone-aware DateTime if possible .如果可能,将本地NaiveDateTime转换为可识别时区的DateTime

emphasis mine, some naive datetimes don't map any date in the timezone, and some are ambiguous (can map to multiple dates in the timezone).强调我的, 一些天真的日期时间不会 map 时区的任何日期,有些是模棱两可的(可以 map 到时区中的多个日期)。 You need to decide whether and how you will handle those situations.您需要决定是否以及如何处理这些情况。

That aside,除此之外,

But generally how do I convert my Kolkata datetime to a DateTime<Utc> instance?但通常如何将我的Kolkata日期时间转换为DateTime<Utc>实例?

As noted above, you don't currently have a "Kolkata datetime", so you need to fix that.如上所述,您目前没有“加尔各答日期时间”,因此您需要修复它。 I'm not actually sure why you're going through NaiveDateTime then localising that since TimeZone has the ymd / and_hms builders.我实际上不确定您为什么要通过NaiveDateTime然后将其本地化,因为TimeZone具有ymd / and_hms构建器。 So you should be able to directly ask for "October 10th 2020 at 10:10:10 in the Kolkata timezone":因此,您应该可以直接询问“加尔各答时区 2020 年 10 月 10 日 10:10:10”:

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

Then, you can use with_timezone to "move" the datetime around.然后,您可以使用with_timezone来“移动”日期时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM