File tree Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Expand file tree Collapse file tree 2 files changed +37
-0
lines changed Original file line number Diff line number Diff 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
394410impl fmt:: Debug for crate :: DateTime {
Original file line number Diff line number Diff line change 1+ use std:: time:: Duration ;
2+
13use crate :: tests:: LOCK ;
24
35#[ test]
@@ -38,3 +40,22 @@ fn datetime_to_rfc3339() {
3840fn 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+ }
You can’t perform that action at this time.
0 commit comments