yfunc_rust/
ytime.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
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())
    }
}