time.rs (1449B)
1 use std::time::{SystemTime, UNIX_EPOCH}; 2 3 pub fn time_ago_since(timestamp: u64) -> String { 4 let now = SystemTime::now() 5 .duration_since(UNIX_EPOCH) 6 .expect("Time went backwards") 7 .as_secs(); 8 9 // Determine if the timestamp is in the future or the past 10 let duration = if now >= timestamp { 11 now.saturating_sub(timestamp) 12 } else { 13 timestamp.saturating_sub(now) 14 }; 15 16 let future = timestamp > now; 17 let relstr = if future { "+" } else { "" }; 18 19 let years = duration / 31_536_000; // seconds in a year 20 if years >= 1 { 21 return format!("{}{}yr", relstr, years); 22 } 23 24 let months = duration / 2_592_000; // seconds in a month (30.44 days) 25 if months >= 1 { 26 return format!("{}{}mth", relstr, months); 27 } 28 29 let weeks = duration / 604_800; // seconds in a week 30 if weeks >= 1 { 31 return format!("{}{}wk", relstr, weeks); 32 } 33 34 let days = duration / 86_400; // seconds in a day 35 if days >= 1 { 36 return format!("{}{}d", relstr, days); 37 } 38 39 let hours = duration / 3600; // seconds in an hour 40 if hours >= 1 { 41 return format!("{}{}h", relstr, hours); 42 } 43 44 let minutes = duration / 60; // seconds in a minute 45 if minutes >= 1 { 46 return format!("{}{}m", relstr, minutes); 47 } 48 49 let seconds = duration; 50 if seconds >= 3 { 51 return format!("{}{}s", relstr, seconds); 52 } 53 54 "now".to_string() 55 }