proto_types/timestamp/
timestamp_impls.rs1use std::time::SystemTime;
2
3use crate::{Duration, Timestamp};
4
5#[cfg(not(feature = "chrono"))]
6impl crate::Timestamp {
7 pub fn format(&self) -> String {
10 self.to_string()
11 }
12}
13
14#[cfg(feature = "chrono")]
15mod chrono {
16 use chrono::Utc;
17
18 use crate::{timestamp::TimestampError, Timestamp};
19
20 impl Timestamp {
21 pub fn format(&self, string: &str) -> Result<String, TimestampError> {
23 let chrono_timestamp: chrono::DateTime<Utc> = (*self).try_into()?;
24
25 Ok(chrono_timestamp.format(string).to_string())
26 }
27
28 pub fn as_datetime_utc(&self) -> Result<chrono::DateTime<Utc>, TimestampError> {
30 (*self).try_into()
31 }
32 }
33}
34
35impl Timestamp {
36 pub fn now() -> Self {
38 SystemTime::now().into()
39 }
40
41 pub fn new(seconds: i64, nanos: i32) -> Self {
43 Timestamp { seconds, nanos }
44 }
45
46 pub fn is_within_range_from_now(&self, range: Duration) -> bool {
48 (Timestamp::now() + range) >= *self && (Timestamp::now() - range) <= *self
49 }
50
51 pub fn is_within_future_range(&self, range: Duration) -> bool {
53 (Timestamp::now() + range) >= *self
54 }
55
56 pub fn is_within_past_range(&self, range: Duration) -> bool {
58 (Timestamp::now() - range) <= *self
59 }
60
61 pub fn is_future(&self) -> bool {
63 *self > Self::now()
64 }
65
66 pub fn is_past(&self) -> bool {
68 *self < Self::now()
69 }
70}