如何将时间`DateTime <Local>`实例转换为`DateTime <Utc>`?

时间:2019-07-04 12:23:02

标签: time rust

之前有question要求以其他方式进行转换(Utc -> Local)


我正在尝试将Local日期时间转换为Utc时间:

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

我目前期望使用类似local.to_utc()的API。也许我可以实现TryFrom特性来进行这种转换。

如何将Local日期时间转换为Utc日期时间?

3 个答案:

答案 0 :(得分:4)

Chrono提供TimeZone特性,其特征为//global object in this runtime env is 'window' var obj1 = { //global scope obj1 value: 'a' } var obj2 = { //global scope obj2 value: 'b' } function change(obj1, obj2) { //js = "pass by copy of reference" obj1 = obj2 //obj1's value is now a reference (aka an address in memory) to global obj2 console.log(typeof obj1) //logs 'object', (meaning local var obj1's value is a reference ) obj1.value = 'c' //global obj2 value changed. console.log(window.obj2) //logs 'value': 'c' console.log(window.obj1) //logs 'value': 'a' } change(obj1, obj2); console.log(obj1.value) //logs 'a' console.log(obj2.value) //logs 'c'

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);
}

答案 1 :(得分:2)

从chrono 0.4.7开始,现在可以用一种更加干净的方式来解决它:

use chrono::prelude::*;

fn main() {
    let utc = Utc::now();
    let local = Local::now();
    let converted: DateTime<Utc> = DateTime::from(local);
    println!("{}\n{}", utc, converted);
}

输出为:

2019-07-30 18:19:27.176827 UTC
2019-07-30 18:19:27.176836 UTC

答案 2 :(得分:0)

您可以使用 chrono::DateTime::with_timezone 将任何 DateTime 转换为另一个时区。

它适用于实现 TimeZone 的结构: chrono::Localchrono::Utc。和chrono_tz::Tz

示例:

#![forbid(unsafe_code)]
use chrono::{DateTime, Local, Utc};

fn main() {
    let local_now: DateTime<Local> = Local::now();
    let utc_now: DateTime<Utc> = local_now.with_timezone(&Utc);
    println!("local = {}", local_now);
    println!("utc = {}", utc_now);
}
$ cargo run --bin example
local = 2021-07-01 15:45:26.251802 -07:00
utc = 2021-07-01 22:45:26.251802 UTC