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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
use chrono::{DateTime, Duration, FixedOffset, Utc};
use serde::{Serialize, Serializer};

use crate::prelude::*;

#[derive(Debug)]
pub struct YTime(DateTime<Utc>);

impl YTime {

    pub fn origin(&self) -> DateTime<Utc> {
        self.0
    }

    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(|e|
            err!("build YTime from rfc3339 format string failed").trace(
                ctx!("build YTime from rfc3339 format string: DateTime::parse_from_rfc3339 failed", rfc3339_time_str, e)
            )
        )?;
        let utc = dt.with_timezone(&Utc);
        Ok(Self(utc))
    }

    pub fn to_str(&self) -> String {
        self.0.to_rfc3339()
    }

    pub fn east8(&self) -> YRes<String> {
        let offset = FixedOffset::east_opt(8 * 3600).ok_or(
            err!("get time string of YTime in east8 timezone failed").trace(
                ctx!("get time string of YTime in east8 timezone: FixedOffset::east_opt failed")
            )
        )?;
        let east8_time = self.0.with_timezone(&offset);
        Ok(east8_time.format("%Y-%m-%d %H:%M:%S").to_string())
    }

    pub fn duration(&self, seconds: i64) -> YTime {
        YTime(self.0 + Duration::seconds(seconds))
    }

    pub fn timestamp(&self) -> i64 {
        self.0.timestamp_millis()
    }

}

impl Serialize for YTime {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_str())
    }
}