Skip to content

Commit 9899785

Browse files
ethanfreyuint
authored andcommitted
Add seconds() method to Timestamp
1 parent 1e0a726 commit 9899785

File tree

1 file changed

+16
-1
lines changed

1 file changed

+16
-1
lines changed

packages/std/src/timestamp.rs

+16-1
Original file line numberDiff line numberDiff line change
@@ -42,14 +42,21 @@ impl Timestamp {
4242
}
4343

4444
/// Returns nanoseconds since epoch
45+
#[inline]
4546
pub fn nanos(&self) -> u64 {
4647
self.0.u64()
4748
}
49+
50+
/// Returns seconds since epoch (truncate nanoseconds)
51+
#[inline]
52+
pub fn seconds(&self) -> u64 {
53+
self.0.u64() / 1_000_000_000
54+
}
4855
}
4956

5057
impl fmt::Display for Timestamp {
5158
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
52-
let whole = self.nanos() / 1_000_000_000;
59+
let whole = self.seconds();
5360
let fractional = self.nanos() % 1_000_000_000;
5461
write!(f, "{}.{:09}", whole, fractional)
5562
}
@@ -131,6 +138,14 @@ mod tests {
131138
assert_eq!(sum.nanos(), 0);
132139
}
133140

141+
#[test]
142+
fn timestamp_seconds() {
143+
let sum = Timestamp::from_nanos(987654321000);
144+
assert_eq!(sum.seconds(), 987);
145+
let sum = Timestamp::from_seconds(1234567).plus_nanos(8765436);
146+
assert_eq!(sum.seconds(), 1234567);
147+
}
148+
134149
#[test]
135150
fn timestamp_implements_display() {
136151
let embedded = format!("Time: {}", Timestamp::from_nanos(0));

0 commit comments

Comments
 (0)