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