damus

nostr ios client
git clone git://jb55.com/damus
Log | Files | Refs | README | LICENSE

TimeAgo.swift (1941B)


      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, _ calendar: Calendar = Calendar.current) -> String {
     11 
     12     let now = Date()
     13     let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfMonth, .month, .year]
     14 
     15     let components = (calendar as NSCalendar).components(unitFlags, from: date, to: now, options: [])
     16 
     17     let formatter = DateComponentsFormatter()
     18     formatter.unitsStyle = .abbreviated
     19     formatter.maximumUnitCount = 1
     20     formatter.allowedUnits = unitFlags
     21 
     22     // Manually format date component from only the most significant time unit because
     23     // DateComponentsFormatter rounds up by default.
     24 
     25     if let year = components.year, year >= 1 {
     26         return formatter.string(from: DateComponents(calendar: calendar, year: year))!
     27     }
     28 
     29     if let month = components.month, month >= 1 {
     30         return formatter.string(from: DateComponents(calendar: calendar, month: month))!
     31     }
     32 
     33     if let week = components.weekOfMonth, week >= 1 {
     34         return formatter.string(from: DateComponents(calendar: calendar, weekOfMonth: week))!
     35     }
     36 
     37     if let day = components.day, day >= 1 {
     38         return formatter.string(from: DateComponents(calendar: calendar, day: day))!
     39     }
     40 
     41     if let hour = components.hour, hour >= 1 {
     42         return formatter.string(from: DateComponents(calendar: calendar, hour: hour))!
     43     }
     44 
     45     if let minute = components.minute, minute >= 1 {
     46         return formatter.string(from: DateComponents(calendar: calendar, minute: minute))!
     47     }
     48 
     49     if let second = components.second, second >= 3 {
     50         return formatter.string(from: DateComponents(calendar: calendar, second: second))!
     51     }
     52 
     53     let bundle = bundleForLocale(locale: calendar.locale ?? Locale.current)
     54     return NSLocalizedString("now", bundle: bundle, comment: "String indicating that a given timestamp just occurred")
     55 }