【发布时间】:2020-07-25 11:47:45
【问题描述】:
如何将字符串转换为chrono::DateTime 或chrono::NaiveDateTime
ParseError(NotEnough) 或 ParseError(TooShort) 是什么意思?
【问题讨论】:
标签: rust rust-chrono
如何将字符串转换为chrono::DateTime 或chrono::NaiveDateTime
ParseError(NotEnough) 或 ParseError(TooShort) 是什么意思?
【问题讨论】:
标签: rust rust-chrono
将字符串转换为 Chrono 对象时,您必须知道字符串的输入格式包含哪些部分。
这些部分是:日期、时间、时区
例子:
ParseError(NotEnough) 在没有足够的信息来填充整个对象时出现。例如,缺少日期、时间或时区。
当格式与字符串不匹配时,您会收到 ParseError(TooShort) 或 ParseError(Invalid) 错误。
字符串格式的规范,例如"%Y-%m-%d %H:%M:%S":https://docs.rs/chrono/latest/chrono/format/strftime/index.html
要转换 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 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);
【讨论】: