From bf34175560076e3b112e9186943cf105e8d94726 Mon Sep 17 00:00:00 2001 From: William Casarin Date: Tue, 27 Aug 2024 14:09:14 +0300 Subject: [PATCH] time: add future timestamp formatting +10s for 10 seconds in the future, etc This can happen sometimes Signed-off-by: William Casarin --- src/time.rs | 26 +++++++++++++++++--------- 1 file changed, 17 insertions(+), 9 deletions(-) diff --git a/src/time.rs b/src/time.rs index 64cea97..dfb0c0b 100644 --- a/src/time.rs +++ b/src/time.rs @@ -1,46 +1,54 @@ use std::time::{SystemTime, UNIX_EPOCH}; -/// Show a relative time string based on some timestamp pub fn time_ago_since(timestamp: u64) -> String { let now = SystemTime::now() .duration_since(UNIX_EPOCH) .expect("Time went backwards") .as_secs(); - let duration = now.saturating_sub(timestamp); + + // Determine if the timestamp is in the future or the past + let duration = if now >= timestamp { + now.saturating_sub(timestamp) + } else { + timestamp.saturating_sub(now) + }; + + let future = timestamp > now; + let relstr = if future { "+" } else { "" }; let years = duration / 31_536_000; // seconds in a year if years >= 1 { - return format!("{}yr", years); + return format!("{}{}yr", relstr, years); } let months = duration / 2_592_000; // seconds in a month (30.44 days) if months >= 1 { - return format!("{}mth", months); + return format!("{}{}mth", relstr, months); } let weeks = duration / 604_800; // seconds in a week if weeks >= 1 { - return format!("{}wk", weeks); + return format!("{}{}wk", relstr, weeks); } let days = duration / 86_400; // seconds in a day if days >= 1 { - return format!("{}d", days); + return format!("{}{}d", relstr, days); } let hours = duration / 3600; // seconds in an hour if hours >= 1 { - return format!("{}h", hours); + return format!("{}{}h", relstr, hours); } let minutes = duration / 60; // seconds in a minute if minutes >= 1 { - return format!("{}m", minutes); + return format!("{}{}m", relstr, minutes); } let seconds = duration; if seconds >= 3 { - return format!("{}s", seconds); + return format!("{}{}s", relstr, seconds); } "now".to_string()