From 5ce3e8381a25399de5f2017cdb9d39dda339b85a Mon Sep 17 00:00:00 2001 From: Ian Jackson Date: Sat, 17 Oct 2020 00:04:14 +0100 Subject: [PATCH] some timezones shown Signed-off-by: Ian Jackson --- demo/test.table.toml | 2 ++ src/gamestate.rs | 4 +--- src/tz.rs | 33 +++++++++++++++++++++++++++++---- 3 files changed, 32 insertions(+), 7 deletions(-) diff --git a/demo/test.table.toml b/demo/test.table.toml index 3f657804..b67890d8 100644 --- a/demo/test.table.toml +++ b/demo/test.table.toml @@ -2,6 +2,8 @@ # SPDX-License-Identifier: AGPL-3.0-or-later # There is NO WARRANTY. +timezone = "Europe/London" + [[players]] nick = "alice" access = "FixedToken" diff --git a/src/gamestate.rs b/src/gamestate.rs index 7e296629..233496de 100644 --- a/src/gamestate.rs +++ b/src/gamestate.rs @@ -171,9 +171,7 @@ impl Timestamp { } pub fn render(&self, tz: &Timezone) -> String { - let mut s = String::with_capacity(30); - tz.format(*self, &mut s).unwrap(); - s + tz.format(*self) } } diff --git a/src/tz.rs b/src/tz.rs index 39f958cf..863b3155 100644 --- a/src/tz.rs +++ b/src/tz.rs @@ -21,10 +21,35 @@ impl Timezone { pub fn name(&self) -> &str { &self.0.name } - #[throws(fmt::Error)] - pub fn format(&self, ts: Timestamp, w: &mut W) { - write!(w, "TS{:?}(@{:?})", ts, &self)? -// let ctz = chrono::offset::Utc; + + // Oh my god this API is awful! + + #[throws(as Option)] + fn format_tz<'r, TZ: chrono::TimeZone>( + tz: &TZ, ts: Timestamp, fmt: &'r str + ) -> chrono::format::DelayedFormat> + where ::Offset : Display + { + use chrono::DateTime; + let dt = tz.timestamp_opt(ts.0.try_into().ok()?, 0).single()?; + DateTime::format(&dt, fmt) + } + + pub fn format(&self, ts: Timestamp) -> String { + match (||{ + let fmt = "%Y-%m-%d %H:%M:%S %z"; + let df = match &self.0.ctz { + Some(ctz) => Timezone::format_tz(ctz, ts, fmt), + None => Timezone::format_tz(&chrono::offset::Utc, ts, fmt), + } + .ok_or_else( + || format!("timestamp {} out of range!", &ts.0) + )?; + Ok(format!("{}", df)) + })() { + Ok(s) => s, + Err(s) => s, + } } pub fn default_todo() -> Self { -- 2.30.2