Browse Source

ics: refactor into Timestamp::from_str()

master
Astro 5 months ago
parent
commit
ba5b4de68d
  1. 24
      libticker/src/ics/mod.rs

24
libticker/src/ics/mod.rs

@ -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 {

Loading…
Cancel
Save