use chrono::{DateTime, Duration, FixedOffset, Utc};
use serde::{Serialize, Serializer};
use crate::prelude::*;
#[derive(Debug)]
pub struct YTime(DateTime<Utc>);
impl YTime {
pub fn now() -> Self {
Self(Utc::now())
}
pub fn from_str(rfc3339_time_str: &str) -> YRes<Self> {
let dt = DateTime::parse_from_rfc3339(rfc3339_time_str).map_err(|err|
err!(ParseError::"YTime.from_str": "parse time string failed", rfc3339_time_str, err)
)?;
let utc = dt.with_timezone(&Utc);
Ok(Self(utc))
}
pub fn to_str(&self) -> String {
self.0.to_rfc3339()
}
pub fn east8(&self) -> String {
let offset = FixedOffset::east(8 * 3600);
let east8_time = self.0.with_timezone(&offset);
east8_time.format("%Y-%m-%d %H:%M:%S").to_string()
}
pub fn duration(&self, seconds: i64) -> YTime {
YTime(self.0 + Duration::seconds(seconds))
}
}
impl Serialize for YTime {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&self.to_str())
}
}