stablesats_shared/
time.rs

1use chrono::{prelude::*, Duration};
2use serde::{Deserialize, Serialize};
3
4#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
5#[serde(transparent)]
6pub struct TimeStamp(#[serde(with = "chrono::serde::ts_seconds")] DateTime<Utc>);
7impl TimeStamp {
8    pub fn now() -> Self {
9        Self(Utc::now())
10    }
11
12    pub fn duration_since(&self) -> Duration {
13        &Self::now() - self
14    }
15}
16impl PartialOrd for TimeStamp {
17    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
18        self.0.partial_cmp(&other.0)
19    }
20}
21impl std::fmt::Display for TimeStamp {
22    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
23        write!(f, "{}", self.0.timestamp())
24    }
25}
26impl std::ops::Sub for &TimeStamp {
27    type Output = Duration;
28    fn sub(self, other: Self) -> Self::Output {
29        self.0.signed_duration_since(other.0)
30    }
31}
32impl std::ops::Sub for TimeStamp {
33    type Output = Duration;
34    fn sub(self, other: Self) -> Self::Output {
35        self.0.signed_duration_since(other.0)
36    }
37}
38
39#[derive(Clone, PartialEq, Debug, Serialize, Deserialize)]
40#[serde(transparent)]
41pub struct TimeStampMilliStr(String);
42impl TryFrom<&TimeStampMilliStr> for TimeStamp {
43    type Error = std::num::ParseIntError;
44
45    fn try_from(value: &TimeStampMilliStr) -> Result<Self, Self::Error> {
46        let millis = value.0.parse::<i64>()?;
47        let naive = NaiveDateTime::from_timestamp(millis / 1000, 0);
48        let datetime: DateTime<Utc> = DateTime::from_utc(naive, Utc);
49        Ok(Self(datetime))
50    }
51}