Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

datetime

rust

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.

like image 481
Byron Avatar asked Feb 26 '15 16:02

Byron


1 Answers

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).

like image 76
Kang Seonghoon Avatar answered Sep 30 '22 12:09

Kang Seonghoon