ics: refactor into Timestamp::from_str()

This commit is contained in:
Astro 2021-05-24 23:16:44 +02:00
parent 1c47540a65
commit ba5b4de68d
1 changed files with 17 additions and 7 deletions

View File

@ -1,4 +1,5 @@
use std::collections::HashMap;
use std::str::FromStr;
use chrono::{NaiveDate, NaiveDateTime};
mod tokenizer;
@ -36,13 +37,7 @@ impl<'a> GetValue<'a, String> for Object {
impl<'a> GetValue<'a, Timestamp> for Object {
fn get(&self, key: &'_ str) -> Option<Timestamp> {
let s = self.get(key)?;
NaiveDateTime::parse_from_str(s, "%Y%m%dT%H%M%SZ")
.or_else(|_| NaiveDateTime::parse_from_str(s, "%Y%m%dT%H%M%S"))
.map(Timestamp::DateTime)
.or_else(|_|
NaiveDate::parse_from_str(s, "%Y%m%d")
.map(Timestamp::Date)
)
Timestamp::from_str(s)
.map_err(|e| println!("Cannot parse date: {:?}", e))
.ok()
}
@ -54,6 +49,21 @@ pub enum Timestamp {
DateTime(NaiveDateTime),
}
impl FromStr for Timestamp {
type Err = String;
fn from_str(s: &'_ str) -> Result<Self, Self::Err> {
NaiveDateTime::parse_from_str(s, "%Y%m%dT%H%M%SZ")
.or_else(|_| NaiveDateTime::parse_from_str(s, "%Y%m%dT%H%M%S"))
.map(Timestamp::DateTime)
.or_else(|_|
NaiveDate::parse_from_str(s, "%Y%m%d")
.map(Timestamp::Date)
)
.map_err(|e| format!("Cannot parse date: {:?}", e))
}
}
impl Timestamp {
pub fn or_hms(self, hour: u32, min: u32, sec: u32) -> NaiveDateTime {
match self {