Skip to main content

dvm_api/
timestamp.rs

1use serde::{Deserialize, Serialize};
2
3/// A point in time: milliseconds since the Unix epoch, UTC.
4#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
5#[cfg_attr(feature = "typescript", derive(ts_rs::TS))]
6#[cfg_attr(feature = "typescript", ts(export_to = "controller-api.ts"))]
7#[serde(transparent)]
8pub struct Timestamp(i64);
9
10impl Timestamp {
11    pub fn from_unix_millis(millis: i64) -> Self {
12        Self(millis)
13    }
14
15    pub fn unix_millis(self) -> i64 {
16        self.0
17    }
18
19    /// The host's clock. Not in the browser, which has no `SystemTime`.
20    #[cfg(not(target_arch = "wasm32"))]
21    pub fn now() -> Self {
22        let since_epoch = std::time::SystemTime::now()
23            .duration_since(std::time::UNIX_EPOCH)
24            .expect("the clock is after 1970");
25        Self(i64::try_from(since_epoch.as_millis()).expect("milliseconds fit an i64"))
26    }
27}