There is a question asked before for the conversion in the other way(Utc -> Local)
I am trying to convert Local
datetime into Utc
time:
use chrono::{Local, UTC, TimeZone};
let utc = chrono::UTC::now(); // 2019-07-04 15:13:19.014970700
let local = chrono::Local::now(); // 2019-07-04 17:13:19.014970700 +03:00
I am currently expecting some API like local.to_utc()
. Maybe I can implement a TryFrom
trait for such conversion.
How can I convert Local
datetime to Utc
datetime?
Chrono provides the TimeZone
trait which has the method from_local_datetime
.
use chrono::prelude::*;
fn main() {
let local = Local::now();
let utc = Utc
.from_local_datetime(&local.naive_local())
.single()
.unwrap();
dbg!(local.naive_local());
dbg!(utc);
}
On my local machine it gives me:
[src/main.rs:10] local.naive_local() = 2019-07-04T14:25:15.093909965
[src/main.rs:11] utc = 2019-07-04T12:25:15.093909965Z
As of chrono 0.4.7, this is now taken care of in a much cleaner way:
use chrono::prelude::*;
fn main() {
let utc = Utc::now();
let local = Local::now();
let converted: DateTime<Utc> = DateTime::from(local);
println!("{}\n{}", utc, converted);
}
This gives an output of:
2019-07-30 18:19:27.176827 UTC
2019-07-30 18:19:27.176836 UTC
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With