Skip to content

Commit fa5eda0

Browse files
committed
feat: add display_unix_timestamp in short mode
1 parent 41a61e3 commit fa5eda0

File tree

1 file changed

+49
-2
lines changed

1 file changed

+49
-2
lines changed

src/display_unix_epoch.rs

Lines changed: 49 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,14 +22,51 @@ use chrono::Utc;
2222
pub struct DisplayUnixTimeStamp {
2323
/// The duration since the UNIX epoch.
2424
duration: Duration,
25+
26+
in_millis: bool,
27+
28+
with_timezone: bool,
2529
}
2630

2731
impl fmt::Display for DisplayUnixTimeStamp {
2832
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2933
let system_time = UNIX_EPOCH + self.duration;
3034
let datetime: DateTime<Utc> = system_time.into();
3135

32-
write!(f, "{}", datetime.format("%Y-%m-%dT%H:%M:%S%.6fZ%z"))
36+
let fmt = if self.in_millis {
37+
if self.with_timezone {
38+
"%Y-%m-%dT%H:%M:%S%.3fZ%z"
39+
} else {
40+
"%Y-%m-%dT%H:%M:%S%.3f"
41+
}
42+
} else if self.with_timezone {
43+
"%Y-%m-%dT%H:%M:%S%.6fZ%z"
44+
} else {
45+
"%Y-%m-%dT%H:%M:%S%.6f"
46+
};
47+
48+
write!(f, "{}", datetime.format(fmt))
49+
}
50+
}
51+
52+
impl DisplayUnixTimeStamp {
53+
pub fn new(duration: Duration) -> Self {
54+
Self {
55+
duration,
56+
in_millis: false,
57+
with_timezone: true,
58+
}
59+
}
60+
61+
pub fn in_millis(self, in_millis: bool) -> Self {
62+
Self { in_millis, ..self }
63+
}
64+
65+
pub fn with_timezone(self, with_timezone: bool) -> Self {
66+
Self {
67+
with_timezone,
68+
..self
69+
}
3370
}
3471
}
3572

@@ -50,11 +87,18 @@ impl fmt::Display for DisplayUnixTimeStamp {
5087
/// ```
5188
pub trait DisplayUnixTimeStampExt {
5289
fn display_unix_timestamp(&self) -> DisplayUnixTimeStamp;
90+
91+
/// Display the duration since the UNIX epoch in milliseconds without timezone.
92+
fn display_unix_timestamp_short(&self) -> DisplayUnixTimeStamp {
93+
self.display_unix_timestamp()
94+
.in_millis(true)
95+
.with_timezone(false)
96+
}
5397
}
5498

5599
impl DisplayUnixTimeStampExt for Duration {
56100
fn display_unix_timestamp(&self) -> DisplayUnixTimeStamp {
57-
DisplayUnixTimeStamp { duration: *self }
101+
DisplayUnixTimeStamp::new(*self)
58102
}
59103
}
60104

@@ -73,5 +117,8 @@ mod tests {
73117
let epoch = Duration::from_millis(1723102819023);
74118
let display = epoch.display_unix_timestamp();
75119
assert_eq!(format!("{}", display), "2024-08-08T07:40:19.023000Z+0000");
120+
121+
let display = epoch.display_unix_timestamp_short();
122+
assert_eq!(format!("{}", display), "2024-08-08T07:40:19.023");
76123
}
77124
}

0 commit comments

Comments
 (0)