chj_unix_util/
timestamp_formatter.rs

1use std::time::SystemTime;
2
3use chrono::{DateTime, Local, Utc};
4
5#[derive(Debug, Clone, clap::Args)]
6pub struct TimestampFormatter {
7    /// Whether rfc3339 format is to be used (default: whatever chrono
8    /// uses for `Display`).
9    #[clap(long)]
10    pub use_rfc3339: bool,
11
12    /// If true, write log time stamps in the local time zone.
13    /// Default: in UTC.
14    #[clap(long)]
15    pub local_time: bool,
16}
17
18impl TimestampFormatter {
19    pub fn format_systemtime(&self, t: SystemTime) -> String {
20        let Self {
21            use_rfc3339,
22            local_time,
23        } = self;
24        if *local_time {
25            let t: DateTime<Local> = t.into();
26            if *use_rfc3339 {
27                t.to_rfc3339()
28            } else {
29                t.to_string()
30            }
31        } else {
32            let t: DateTime<Utc> = t.into();
33            if *use_rfc3339 {
34                t.to_rfc3339()
35            } else {
36                t.to_string()
37            }
38        }
39    }
40}