TimeAgo.swift (1019B)
1 // 2 // TimeAgo.swift 3 // damus 4 // 5 // Created by William Casarin on 2022-04-16. 6 // 7 8 import Foundation 9 10 public func time_ago_since(_ date: Date) -> String { 11 12 let calendar = Calendar.current 13 let now = Date() 14 let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfYear, .month, .year] 15 let components = (calendar as NSCalendar).components(unitFlags, from: date, to: now, options: []) 16 17 if let year = components.year, year >= 1 { 18 return "\(year)yr" 19 } 20 21 if let month = components.month, month >= 1 { 22 return "\(month)mth" 23 } 24 25 if let week = components.weekOfYear, week >= 1 { 26 return "\(week)wk" 27 } 28 29 if let day = components.day, day >= 1 { 30 return "\(day)d" 31 } 32 33 if let hour = components.hour, hour >= 1 { 34 return "\(hour)h" 35 } 36 37 if let minute = components.minute, minute >= 1 { 38 return "\(minute)m" 39 } 40 41 if let second = components.second, second >= 3 { 42 return "\(second)s" 43 } 44 45 return "now" 46 }