commit 42d134e098e193bda1b9b8e926ea4321e1a05791
parent 0225251e5d43039e316b54b728ae59f7db242553
Author: alex wennerberg <alex@alexwennerberg.com>
Date: Sun, 20 Mar 2022 14:06:39 -0700
add timeago
Diffstat:
A | time.rs | | | 35 | +++++++++++++++++++++++++++++++++++ |
1 file changed, 35 insertions(+), 0 deletions(-)
diff --git a/time.rs b/time.rs
@@ -0,0 +1,35 @@
+use std::time::{SystemTime, UNIX_EPOCH};
+const SOLAR_YEAR_SECS: u64 = 31556926;
+
+pub fn timeago(unixtime: u64) -> String {
+ let current_time = SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .unwrap()
+ .as_secs();
+ if unixtime > current_time {
+ return "in the future".to_owned();
+ }
+ let diff = current_time - unixtime;
+ let amount: u64;
+ let metric: &str;
+ // if diff < 60 {
+ // amount = diff;
+ // metric = "second";
+ // } else if diff < 60 * 60 {
+ // amount = diff / 60;
+ // metric = "minute";
+ if diff < 60 * 60 * 24 {
+ amount = diff / (60 * 60);
+ metric = "hour";
+ } else if diff < SOLAR_YEAR_SECS * 2 {
+ amount = diff / (60 * 60 * 24);
+ metric = "day";
+ } else {
+ amount = diff / SOLAR_YEAR_SECS * 2;
+ metric = "year";
+ }
+ match amount {
+ 1 => format!("{} {} ago", amount, metric),
+ _ => format!("{} {}s ago", amount, metric),
+ }
+}