Skip to content

Commit

Permalink
RUST-1677 Add duration_since methods to DateTime (#417)
Browse files Browse the repository at this point in the history
  • Loading branch information
isabelatkinson authored Jun 9, 2023
1 parent b637094 commit b243db1
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
16 changes: 16 additions & 0 deletions src/datetime.rs
Original file line number Diff line number Diff line change
Expand Up @@ -389,6 +389,22 @@ impl crate::DateTime {
})?;
Ok(Self::from_time_0_3(odt))
}

/// Returns the time elapsed since `earlier`, or `None` if the given `DateTime` is later than
/// this one.
pub fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
if earlier.0 > self.0 {
return None;
}
Some(Duration::from_millis((self.0 - earlier.0) as u64))
}

/// Returns the time elapsed since `earlier`, or a [`Duration`] of zero if the given `DateTime`
/// is later than this one.
pub fn saturating_duration_since(self, earlier: Self) -> Duration {
self.checked_duration_since(earlier)
.unwrap_or(Duration::ZERO)
}
}

impl fmt::Debug for crate::DateTime {
Expand Down
21 changes: 21 additions & 0 deletions src/tests/datetime.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::time::Duration;

use crate::tests::LOCK;

#[test]
Expand Down Expand Up @@ -38,3 +40,22 @@ fn datetime_to_rfc3339() {
fn invalid_datetime_to_rfc3339() {
assert!(crate::DateTime::MAX.try_to_rfc3339_string().is_err());
}

#[test]
fn duration_since() {
let _guard = LOCK.run_concurrently();

let date1 = crate::DateTime::from_millis(100);
let date2 = crate::DateTime::from_millis(1000);

assert_eq!(
date2.checked_duration_since(date1),
Some(Duration::from_millis(900))
);
assert_eq!(
date2.saturating_duration_since(date1),
Duration::from_millis(900)
);
assert!(date1.checked_duration_since(date2).is_none());
assert_eq!(date1.saturating_duration_since(date2), Duration::ZERO);
}

0 comments on commit b243db1

Please sign in to comment.