use std::time::Duration;
use chrono::{DateTime, Utc};
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Timestamp(DateTime<Utc>);
impl Timestamp {
pub fn now() -> Self {
Self(Utc::now())
}
pub fn elapsed(&self) -> Duration {
let elapsed = Utc::now() - self.0;
elapsed.to_std().unwrap_or(Duration::ZERO)
}
pub fn duration_since(&self, earlier: Timestamp) -> Duration {
let d = self.0 - earlier.0;
d.to_std().unwrap_or(Duration::ZERO)
}
pub fn as_datetime(&self) -> DateTime<Utc> {
self.0
}
pub fn as_nanos_since_epoch(&self) -> i64 {
self.0.timestamp_nanos_opt().unwrap_or(0)
}
}
impl std::ops::Add<Duration> for Timestamp {
type Output = Timestamp;
fn add(self, rhs: Duration) -> Timestamp {
Timestamp(self.0 + chrono::Duration::from_std(rhs).unwrap_or(chrono::Duration::zero()))
}
}
impl std::ops::Sub<Timestamp> for Timestamp {
type Output = Duration;
fn sub(self, rhs: Timestamp) -> Duration {
self.duration_since(rhs)
}
}