1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
#[cfg(feature = "local-time")]
mod localtime {
    use std::time::SystemTime;

    /// Return a string representing the current date and time as localtime.
    ///
    /// Available with the `localtime` feature toggle.
    pub fn format_now_datetime_seconds() -> String {
        let t = time::OffsetDateTime::now_utc();
        t.to_offset(time::UtcOffset::local_offset_at(t).unwrap_or(time::UtcOffset::UTC))
            .format(&time::format_description::parse("%F %T").expect("format known to work"))
            .expect("formatting always works")
    }

    /// Return a string representing the current time as localtime.
    ///
    /// Available with the `localtime` feature toggle.
    pub fn format_time_for_messages(time: SystemTime) -> String {
        time::OffsetDateTime::from(time)
            .to_offset(time::UtcOffset::current_local_offset().unwrap_or(time::UtcOffset::UTC))
            .format(&time::format_description::parse("[hour]:[minute]:[second]").expect("format known to work"))
            .expect("formatting always works")
    }
}

/// An `hours:minute:seconds` format.
pub const DATE_TIME_HMS: usize = "00:51:45".len();

#[cfg(not(feature = "local-time"))]
mod utc {
    use super::DATE_TIME_HMS;
    use std::time::SystemTime;
    const DATE_TIME_YMD: usize = "2020-02-13T".len();

    /// Return a string representing the current date and time as UTC.
    ///
    /// Available without the `localtime` feature toggle.
    pub fn format_time_for_messages(time: SystemTime) -> String {
        String::from_utf8_lossy(
            &humantime::format_rfc3339_seconds(time).to_string().as_bytes()
                [DATE_TIME_YMD..DATE_TIME_YMD + DATE_TIME_HMS],
        )
        .into_owned()
    }

    /// Return a string representing the current time as UTC.
    ///
    /// Available without the `localtime` feature toggle.
    pub fn format_now_datetime_seconds() -> String {
        String::from_utf8_lossy(
            &humantime::format_rfc3339_seconds(std::time::SystemTime::now())
                .to_string()
                .as_bytes()[.."2020-02-13T00:51:45".len()],
        )
        .into_owned()
    }
}

#[cfg(feature = "local-time")]
pub use localtime::*;

#[cfg(not(feature = "local-time"))]
pub use utc::*;