time_util/
print.rs

1// Copyright (C) 2021 Daniel Mueller <deso@posteo.net>
2// SPDX-License-Identifier: GPL-3.0-or-later
3
4use std::time::SystemTime;
5
6use chrono::offset::Utc;
7use chrono::DateTime;
8use chrono::SecondsFormat;
9
10
11/// Print a `SystemTime` as a RFC3339 time stamp.
12pub fn print_system_time_to_rfc3339(time: &SystemTime) -> String {
13  DateTime::<Utc>::from(*time).to_rfc3339_opts(SecondsFormat::Millis, true)
14}
15
16
17/// Print a `SystemTime` as a RFC3339 time stamp.
18pub fn print_system_time_to_rfc3339_with_nanos(time: &SystemTime) -> String {
19  // Rust's `SystemTime` internally work with nano seconds and so by
20  // doing the same we hope to have no loss of information.
21  DateTime::<Utc>::from(*time).to_rfc3339_opts(SecondsFormat::Nanos, true)
22}
23
24
25/// Print a `SystemTime` as a RFC3339 time stamp.
26pub fn print_system_time_to_iso8601_date(time: &SystemTime) -> String {
27  DateTime::<Utc>::from(*time).format("%Y-%m-%d").to_string()
28}
29
30
31#[cfg(test)]
32mod tests {
33  use super::*;
34
35  use crate::parse::parse_system_time_from_str;
36
37
38  /// Check that we can format a `SystemTime` as a RFC3339 time stamp.
39  #[test]
40  fn print_rfc3339() {
41    let string = "2018-04-01T12:04:17.050Z";
42    let time = parse_system_time_from_str(string).unwrap();
43    let result = print_system_time_to_rfc3339(&time);
44    assert_eq!(result, string)
45  }
46
47
48  /// Check that we can format a `SystemTime` as a RFC3339 time stamp
49  /// with nanosecond resolution.
50  #[test]
51  fn print_rfc3339_with_nanos() {
52    let string = "2018-04-01T12:04:17.050937231Z";
53    let time = parse_system_time_from_str(string).unwrap();
54    let result = print_system_time_to_rfc3339_with_nanos(&time);
55    assert_eq!(result, string)
56  }
57
58
59  /// Check that we can format a `SystemTime` as an ISO 8601 date.
60  #[test]
61  fn print_iso8601_date() {
62    let string = "2018-05-07T23:59:59Z";
63    let time = parse_system_time_from_str(string).unwrap();
64    let result = print_system_time_to_iso8601_date(&time);
65    assert_eq!(result, "2018-05-07");
66
67    let string = "2018-05-07T00:00:00Z";
68    let time = parse_system_time_from_str(string).unwrap();
69    let result = print_system_time_to_iso8601_date(&time);
70    assert_eq!(result, "2018-05-07");
71  }
72}