Skip to main content

humanize_duration/
prelude.rs

1use crate::types::{DefaultFormatter, DurationParts};
2use crate::{Duration, FormattedDuration, Formatter, Truncate};
3
4pub static SECONDS_IN_YEAR: i64 = 31_556_952; // 31_557_600
5
6pub trait DurationExt {
7	fn human(&self, truncate: Truncate) -> FormattedDuration;
8	fn human_with_format<T: Formatter + 'static>(&self, truncate: Truncate, fmt: T) -> FormattedDuration;
9}
10
11impl DurationExt for time::Duration {
12	fn human(&self, truncate: Truncate) -> FormattedDuration {
13		self.human_with_format(truncate, DefaultFormatter)
14	}
15
16	fn human_with_format<T: Formatter + 'static>(&self, truncate: Truncate, fmt: T) -> FormattedDuration {
17		let duration: Duration = (*self).into();
18		FormattedDuration {
19			duration,
20			truncate_option: truncate,
21			formatter: Box::new(fmt),
22		}
23	}
24}
25
26impl DurationExt for core::time::Duration {
27	fn human(&self, truncate: Truncate) -> FormattedDuration {
28		self.human_with_format(truncate, DefaultFormatter)
29	}
30
31	fn human_with_format<T: Formatter + 'static>(&self, truncate: Truncate, fmt: T) -> FormattedDuration {
32		let duration: Duration = (*self).into();
33		FormattedDuration {
34			duration,
35			truncate_option: truncate,
36			formatter: Box::new(fmt),
37		}
38	}
39}
40
41#[cfg(feature = "chrono")]
42impl DurationExt for chrono::Duration {
43	fn human(&self, truncate: Truncate) -> FormattedDuration {
44		self.human_with_format(truncate, DefaultFormatter)
45	}
46
47	fn human_with_format<T: Formatter + 'static>(&self, truncate: Truncate, fmt: T) -> FormattedDuration {
48		let duration: Duration = (*self).into();
49		FormattedDuration {
50			duration,
51			truncate_option: truncate,
52			formatter: Box::new(fmt),
53		}
54	}
55}
56
57impl From<Duration> for DurationParts {
58	fn from(value: Duration) -> Self {
59		let original_seconds = value.secs;
60		let original_nanos = value.nanos;
61
62		let years = original_seconds / SECONDS_IN_YEAR;
63		let ydays = original_seconds % SECONDS_IN_YEAR;
64		let months = ydays / 2_630_016; // 30.44d
65		let mdays = ydays % 2_630_016;
66		let days = mdays / 86400;
67		let day_secs = mdays % 86400;
68		let hours = day_secs / 3600;
69		let minutes = day_secs % 3600 / 60;
70		let seconds = day_secs % 60;
71		let millis = original_nanos / 1_000_000;
72		let micros = original_nanos / 1000 % 1000;
73		let nanos = original_nanos % 1000;
74
75		DurationParts {
76			original_seconds,
77			original_nanos,
78			years,
79			months,
80			days,
81			hours,
82			minutes,
83			seconds,
84			millis,
85			micros,
86			nanos,
87		}
88	}
89}