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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
use chrono::{DateTime, Utc};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
#[cfg(feature = "tai64")]
use tai64::TAI64N;
use error::Error;
#[cfg_attr(feature = "serializers", derive(Serialize, Deserialize))]
#[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord)]
pub struct Timestamp(DateTime<Utc>);
impl Timestamp {
pub fn now() -> Self {
Timestamp(Utc::now())
}
pub fn unix_epoch() -> Self {
UNIX_EPOCH.into()
}
pub fn duration_since(&self, other: Timestamp) -> Result<Duration, Error> {
self.0
.signed_duration_since(other.0)
.to_std()
.map_err(|_| Error::OutOfRange)
}
pub fn parse_from_rfc3339(s: &str) -> Result<Timestamp, Error> {
Ok(Timestamp(
DateTime::parse_from_rfc3339(s)?.with_timezone(&Utc),
))
}
pub fn to_system_time(&self) -> Result<SystemTime, Error> {
let duration_since_epoch = self.duration_since(Self::unix_epoch())?;
Ok(UNIX_EPOCH + duration_since_epoch)
}
}
impl From<DateTime<Utc>> for Timestamp {
fn from(t: DateTime<Utc>) -> Timestamp {
Timestamp(t)
}
}
impl From<Timestamp> for DateTime<Utc> {
fn from(t: Timestamp) -> DateTime<Utc> {
t.0
}
}
impl From<SystemTime> for Timestamp {
fn from(t: SystemTime) -> Timestamp {
Timestamp(t.into())
}
}
impl From<Timestamp> for SystemTime {
fn from(t: Timestamp) -> SystemTime {
t.to_system_time().unwrap()
}
}
#[cfg(feature = "tai64")]
impl From<TAI64N> for Timestamp {
fn from(t: TAI64N) -> Timestamp {
Timestamp(t.to_datetime_utc())
}
}
#[cfg(feature = "tai64")]
impl From<Timestamp> for TAI64N {
fn from(t: Timestamp) -> TAI64N {
TAI64N::from_datetime_utc(&t.0)
}
}
pub trait ParseTimestamp {
fn parse_timestamp(&self) -> Result<Timestamp, Error>;
}