use chrono::{DateTime, SecondsFormat, Utc};
pub fn format_timestamp(timestamp: &DateTime<Utc>) -> String {
timestamp.to_rfc3339_opts(SecondsFormat::AutoSi, true)
}
#[cfg(test)]
mod tests {
use super::*;
fn at(rfc3339: &str) -> DateTime<Utc> {
rfc3339.parse().unwrap()
}
#[test]
fn test_format_timestamp_uses_the_z_designator() {
let formatted = format_timestamp(&at("2025-01-01T00:00:00+00:00"));
assert_eq!(formatted, "2025-01-01T00:00:00Z");
}
#[test]
fn test_format_timestamp_keeps_only_the_digits_the_value_needs() {
for (input, expected) in [
("2025-01-01T00:00:00Z", "2025-01-01T00:00:00Z"),
("2025-01-01T00:00:00.5Z", "2025-01-01T00:00:00.500Z"),
("2025-01-01T00:00:00.123Z", "2025-01-01T00:00:00.123Z"),
("2025-01-01T00:00:00.000123Z", "2025-01-01T00:00:00.000123Z"),
(
"2025-01-01T00:00:00.000000123Z",
"2025-01-01T00:00:00.000000123Z",
),
] {
assert_eq!(format_timestamp(&at(input)), expected, "{input}");
}
}
#[test]
fn test_format_timestamp_round_trips() {
let now = Utc::now();
assert_eq!(at(&format_timestamp(&now)), now);
}
}