简体   繁体   中英

How do I convert a chrono `DateTime<UTC>` instance to `DateTime<Local>`?

My goal is to convert utc into loc :

use chrono::{Local, UTC, TimeZone};

let utc = chrono::UTC::now();
let loc = chrono::Local::now();

println!("{:?}", utc);
println!("{:?}", loc);

println!("{:?}", utc.with_timezone(&Local));
println!("{:?}", Local.from_utc_datetime(&utc.naive_local()));

... which produced the following output:

2015-02-26T16:22:27.873593Z
2015-02-26T17:22:27.873663+01:00
2015-02-26T15:22:27.873593+00:00
2015-02-26T15:22:27.873593+00:00

The loc time shown in the second row is what I want to see when converting utc .

How do I properly convert a DateTime<UTC> instance to DateTime<Local> ?

Meta

I am using chrono 0.2.2 . In the DateTime.from_utc method it's even telling me I should use the TimeZone trait. However, I am missing something.

Oops, thank you for reporting. This is a bug and registered as the issue #26 . This should be fixed in Chrono 0.2.3.

Besides from the bug, utc.with_timezone(&Local) is indeed a correct way to convert to the local time. There is an important identity that utc.with_timezone(&Local).with_timezone(&UTC) should be equal to utc (except for the exceptional case, where the local time zone has been changed).

Starting with chrono 0.4.7 you can convert them between with using from trait in a simpler way:

use chrono::prelude::*;

fn main() {
    let utc = Utc::now();
    let local = Local::now();
    let converted: DateTime<Local> = DateTime::from(utc);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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