proto_types/timestamp/
timestamp_impls.rs

1use std::time::SystemTime;
2
3use crate::{Duration, Timestamp};
4
5#[cfg(not(feature = "chrono"))]
6impl crate::Timestamp {
7  /// Returns the timestamp in YYYY-MM-DD format.
8  /// The same method, with the `chrono` feature, allows for custom formatting.
9  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    /// Converts this timestamp into a [`chrono::DateTime<Utc>`] struct and calls .format on it with the string argument being given.
22    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    /// Converts this [`Timestamp`] instance to chrono::[`DateTime`](::chrono::DateTime) with [`chrono::Utc`].
29    pub fn as_datetime_utc(&self) -> Result<chrono::DateTime<Utc>, TimestampError> {
30      (*self).try_into()
31    }
32  }
33}
34
35impl Timestamp {
36  /// Returns the current timestamp.
37  pub fn now() -> Self {
38    SystemTime::now().into()
39  }
40
41  /// Creates a new instance.
42  pub fn new(seconds: i64, nanos: i32) -> Self {
43    Timestamp { seconds, nanos }
44  }
45
46  /// Checks whether the Timestamp instance is within the indicated range (positive or negative) from now.
47  pub fn is_within_range_from_now(&self, range: Duration) -> bool {
48    (Timestamp::now() + range) >= *self && (Timestamp::now() - range) <= *self
49  }
50
51  /// Checks whether the Timestamp instance is within the indicated range in the future.
52  pub fn is_within_future_range(&self, range: Duration) -> bool {
53    (Timestamp::now() + range) >= *self
54  }
55
56  /// Checks whether the Timestamp instance is within the indicated range in the past.
57  pub fn is_within_past_range(&self, range: Duration) -> bool {
58    (Timestamp::now() - range) <= *self
59  }
60
61  /// Returns `true` if the timestamp is in the future.
62  pub fn is_future(&self) -> bool {
63    *self > Self::now()
64  }
65
66  /// Returns `true` if the timestamp is in the past.
67  pub fn is_past(&self) -> bool {
68    *self < Self::now()
69  }
70}