rust 使用时间板条箱将UTC RFC3339时间戳转换为本地时间

gcxthw6b  于 2022-12-29  发布在  其他
关注(0)|答案(1)|浏览(163)

过去两天我一直在用头撞time箱子。我找不到,在他们的文档中,如何获取RFC 3339 UTC 2022-12-28T02:11:46Z时间戳并将其转换为America/New_York的本地时间(2022-12-27T21:11:46).我不再使用chrono机箱,因为它有/曾经有一个漏洞,而且它没有像以前那样得到很好的维护。Chrono也依赖于time,但是在它的0.1.x分支中。
My cargo.toml包括time = { version = "0.3", features = ["macros", "parsing", "local-offset"] }行,因此启用我认为需要的功能。

use time::{format_description::well_known::Rfc3339, PrimitiveDateTime};

/// The paramater zulu would be a RFC3339 formatted string.
///
/// ```
/// #use time::{format_description::well_known::Rfc3339, PrimitiveDateTime};
/// assert_eq!("2022-12-27T21:11:46", date_time_local("2022-12-28T02:11:46Z".to_string()));
/// ```
fn date_time_local(zulu: &String) -> String {
    match PrimitiveDateTime::parse(zulu, &Rfc3339) {
        Ok(local) => local.to_string(),
        Err(..) => zulu.to_owned(),
    }
}

我在这儿可没这么走运。

rsaldnfx

rsaldnfx1#

fn main() {
    assert_eq!("2022-12-27 21:11:46", date_time_local(&"2022-12-28T02:11:46Z".to_string()));
}

/// The parameter zulu should be a RFC3339 formatted string.
/// This converts that Zulu timestamp into a local timestamp.
/// ```
/// assert_eq!("2022-12-27 21:11:46", date_time_local("2022-12-28T02:11:46Z".to_string()));
/// ```
fn date_time_local(zulu: &String) -> String {
    use time::{format_description::well_known::Rfc3339, PrimitiveDateTime, UtcOffset};

    // Determine Local TimeZone
    let utc_offset = match UtcOffset::current_local_offset() {
        Ok(utc_offset) => utc_offset,
        Err(..) => return zulu.to_owned(),
    };

    // Parse the given zulu paramater.
    let zulu_parsed = match PrimitiveDateTime::parse(zulu, &Rfc3339) {
        Ok(zulu_parsed) => zulu_parsed.assume_utc(),
        Err(..) => return zulu.to_owned(),
    };

    // Convert zulu to local time offset.
    let parsed = zulu_parsed.to_offset(utc_offset);

    format!(
        "{:04}-{:02}-{:02} {:02}:{:02}:{:02}",
        parsed.year(),
        parsed.month() as u8,
        parsed.day(),
        parsed.hour(),
        parsed.minute(),
        parsed.second()
    )
}

有一个轻微的变化,我删除了日期和时间之间的T

相关问题