Skip to content

Commit b243db1

Browse files
RUST-1677 Add duration_since methods to DateTime (#417)
1 parent b637094 commit b243db1

File tree

2 files changed

+37
-0
lines changed

2 files changed

+37
-0
lines changed

src/datetime.rs

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -389,6 +389,22 @@ impl crate::DateTime {
389389
})?;
390390
Ok(Self::from_time_0_3(odt))
391391
}
392+
393+
/// Returns the time elapsed since `earlier`, or `None` if the given `DateTime` is later than
394+
/// this one.
395+
pub fn checked_duration_since(self, earlier: Self) -> Option<Duration> {
396+
if earlier.0 > self.0 {
397+
return None;
398+
}
399+
Some(Duration::from_millis((self.0 - earlier.0) as u64))
400+
}
401+
402+
/// Returns the time elapsed since `earlier`, or a [`Duration`] of zero if the given `DateTime`
403+
/// is later than this one.
404+
pub fn saturating_duration_since(self, earlier: Self) -> Duration {
405+
self.checked_duration_since(earlier)
406+
.unwrap_or(Duration::ZERO)
407+
}
392408
}
393409

394410
impl fmt::Debug for crate::DateTime {

src/tests/datetime.rs

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,5 @@
1+
use std::time::Duration;
2+
13
use crate::tests::LOCK;
24

35
#[test]
@@ -38,3 +40,22 @@ fn datetime_to_rfc3339() {
3840
fn invalid_datetime_to_rfc3339() {
3941
assert!(crate::DateTime::MAX.try_to_rfc3339_string().is_err());
4042
}
43+
44+
#[test]
45+
fn duration_since() {
46+
let _guard = LOCK.run_concurrently();
47+
48+
let date1 = crate::DateTime::from_millis(100);
49+
let date2 = crate::DateTime::from_millis(1000);
50+
51+
assert_eq!(
52+
date2.checked_duration_since(date1),
53+
Some(Duration::from_millis(900))
54+
);
55+
assert_eq!(
56+
date2.saturating_duration_since(date1),
57+
Duration::from_millis(900)
58+
);
59+
assert!(date1.checked_duration_since(date2).is_none());
60+
assert_eq!(date1.saturating_duration_since(date2), Duration::ZERO);
61+
}

0 commit comments

Comments
 (0)