Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

time

rust

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?

like image 915
Akiner Alkan Avatar asked Jul 04 '19 12:07

Akiner Alkan


2 Answers

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
like image 161
hellow Avatar answered Oct 25 '22 10:10

hellow


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
like image 42
atomos203 Avatar answered Oct 25 '22 10:10

atomos203