use serde::{self, Serialize, Deserialize};
use std::fmt::Display;
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub struct TimeLike(pub(crate) String);
impl Default for TimeLike {
fn default() -> TimeLike {
TimeLike(String::from(""))
}
}
impl Display for TimeLike {
fn fmt(&self, f: &mut ::std::fmt::Formatter) -> ::std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl TimeLike {
pub fn inner(&self) -> &String {
&self.0
}
pub fn inner_mut(&mut self) -> &mut String {
&mut self.0
}
}
#[cfg(feature = "chrono")]
pub mod _impls { use crate::time::TimeLike;
use crate::error::{Result, Error};
use chrono::prelude::*;
use crate::constants::TIMELIKE_FORMAT;
impl TimeLike {
pub fn parse(&self) -> Result<DateTime<Utc>> {
Utc.datetime_from_str(
&self.0, TIMELIKE_FORMAT
).map_err(|e| {
Error::ParseTimeLike {
reason: e.to_string(),
offender: Some(self.0.clone()),
original_err: Some(e)
}
})
}
}
}
#[cfg(feature = "datetime")]
pub use _impls::*;
#[cfg(test)]
mod tests {
use super::TimeLike;
#[test]
#[cfg(feature = "chrono")]
fn timelike_to_datetime_convert() -> Result<(), Box<dyn ::std::error::Error>> {
use chrono::prelude::*;
let time_str = "20200129T042143.000Z";
let time = TimeLike(String::from(time_str));
let dt: DateTime<Utc> = Utc
.ymd(2020, 01, 29).and_hms(04, 21, 43);
assert_eq!(time.parse()?, dt);
Ok(())
}
}