diff --git a/.changelog/unreleased/improvements/1175-unix-timestamp-conversion.md b/.changelog/unreleased/improvements/1175-unix-timestamp-conversion.md new file mode 100644 index 000000000..7b6d6a3a4 --- /dev/null +++ b/.changelog/unreleased/improvements/1175-unix-timestamp-conversion.md @@ -0,0 +1,2 @@ +- `[tendermint]` Added `Time` methods `unix_timestamp` and `unix_timestamp_nanos`. + ([#1175](https://github.com/informalsystems/tendermint-rs/issues/1175)) \ No newline at end of file diff --git a/tendermint/src/time.rs b/tendermint/src/time.rs index 2d8e9732b..ab2895d5d 100644 --- a/tendermint/src/time.rs +++ b/tendermint/src/time.rs @@ -118,6 +118,16 @@ impl Time { timestamp::to_rfc3339_nanos(self.0.assume_utc()) } + /// Return a Unix timestamp in seconds. + pub fn unix_timestamp(&self) -> i64 { + self.0.assume_utc().unix_timestamp() + } + + /// Return a Unix timestamp in nanoseconds. + pub fn unix_timestamp_nanos(&self) -> i128 { + self.0.assume_utc().unix_timestamp_nanos() + } + /// Computes `self + duration`, returning `None` if an overflow occurred. pub fn checked_add(self, duration: Duration) -> Option { let duration = duration.try_into().ok()?; @@ -278,6 +288,19 @@ mod tests { prop_assert_eq!(time, decoded_time); } + #[test] + fn conversion_unix_timestamp_is_safe( + stamp in prop_oneof![ + pbt::time::arb_protobuf_safe_rfc3339_timestamp(), + particular_rfc3339_timestamps(), + ] + ) { + let time: Time = stamp.parse().unwrap(); + let timestamp = time.unix_timestamp(); + let parsed = Time::from_unix_timestamp(timestamp, 0).unwrap(); + prop_assert_eq!(timestamp, parsed.unix_timestamp()); + } + #[test] fn conversion_from_datetime_succeeds_for_4_digit_ce_years( datetime in prop_oneof![