【问题标题】:Rust Chrono parse date String, ParseError(NotEnough) and ParseError(TooShort)Rust Chrono 解析日期字符串、ParseError(NotEnough) 和 ParseError(TooShort)
【发布时间】:2020-07-25 11:47:45
【问题描述】:

如何将字符串转换为chrono::DateTimechrono::NaiveDateTime

ParseError(NotEnough) 或 ParseError(TooShort) 是什么意思?

【问题讨论】:

    标签: rust rust-chrono


    【解决方案1】:

    将字符串转换为 Chrono 对象时,您必须知道字符串的输入格式包含哪些部分。
    这些部分是:日期、时间、时区
    例子:

    ParseError(NotEnough) 在没有足够的信息来填充整个对象时出现。例如,缺少日期、时间或时区。
    当格式与字符串不匹配时,您会收到 ParseError(TooShort)ParseError(Invalid) 错误。

    字符串格式的规范,例如"%Y-%m-%d %H:%M:%S":https://docs.rs/chrono/latest/chrono/format/strftime/index.html

    RFC2822 = 日期 + 时间 + 时区

    要转换 RFC2822 字符串,请使用 parse_from_rfc2822(..) 函数。

    let date_str = "Tue, 1 Jul 2003 10:52:37 +0200";
    let datetime = DateTime::parse_from_rfc2822(date_str).unwrap();
    

    RFC3339 = 日期 + 时间 + 时区

    要转换RFC3339 or ISO 8601 字符串,请使用parse_from_rfc3339(..) 函数。

    let date_str = "2020-04-12T22:10:57+02:00";
    // convert the string into DateTime<FixedOffset>
    let datetime = DateTime::parse_from_rfc3339(date_str).unwrap();
    // convert the string into DateTime<Utc> or other timezone
    let datetime_utc = datetime.with_timezone(&Utc);
    

    日期 + 时间 + 时区(其他或非标准)

    要转换其他 DateTime 字符串,请使用 parse_from_str(..) 函数。

    let date_str = "2020-04-12 22:10:57 +02:00";
    let datetime = DateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S %z").unwrap();
    

    日期 + 时间

    当您没有 TimeZone 时,您需要使用 NaiveDateTime。此对象不存储时区:

    let date_str = "2020-04-12 22:10:57";
    let naive_datetime = NaiveDateTime::parse_from_str(date_str, "%Y-%m-%d %H:%M:%S").unwrap();
    

    日期

    如果我们在哪里解析日期(没有时间),我们可以将其存储在 NaiveDate 中。此对象不存储时间或时区:

    let date_str = "2020-04-12";
    let naive_date = NaiveDate::parse_from_str(date_str, "%Y-%m-%d").unwrap();
    

    时间

    如果我们在哪里解析时间(没有日期),我们可以将其存储在 NaiveTime 中。此对象不存储日期或时区:

    let time_str = "22:10:57";
    let naive_time = NaiveTime::parse_from_str(time_str, "%H:%M:%S").unwrap();
    

    添加日期、时间和/或时区

    如果我们有一些字符串并想添加更多信息,我们可以更改类型。但您必须自己提供这些信息。

    let date_str = "2020-04-12";
    // From string to a NaiveDate
    let naive_date = NaiveDate::parse_from_str(date_str, "%Y-%m-%d").unwrap();
    // Add some default time to convert it into a NaiveDateTime
    let naive_datetime: NaiveDateTime = naive_date.and_hms(0,0,0);
    // Add a timezone to the object to convert it into a DateTime<UTC>
    let datetime_utc = DateTime::<Utc>::from_utc(naive_datetime, Utc);
    

    示例代码游乐场:https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d2b83b3980a5f8fb2e798271766b4541

    【讨论】:

      猜你喜欢
      • 2018-06-16
      • 2016-09-21
      • 1970-01-01
      • 2018-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-05
      • 2018-08-14
      相关资源
      最近更新 更多