Skip to content

Commit

Permalink
time: add future timestamp formatting
Browse files Browse the repository at this point in the history
+10s for 10 seconds in the future, etc

This can happen sometimes

Signed-off-by: William Casarin <[email protected]>
  • Loading branch information
jb55 committed Aug 27, 2024
1 parent ad37602 commit bf34175
Showing 1 changed file with 17 additions and 9 deletions.
26 changes: 17 additions & 9 deletions src/time.rs
Original file line number Diff line number Diff line change
@@ -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()
Expand Down

0 comments on commit bf34175

Please sign in to comment.