TimeAgoFormatter.swift 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. //
  2. // TimeAgoFormatter.swift
  3. // Trio
  4. //
  5. // Created by Cengiz Deniz on 21.05.25.
  6. //
  7. import Foundation
  8. enum TimeAgoFormatter {
  9. /// Returns a user-facing string for how many minutes ago the given date occurred,
  10. /// formatted with non-breaking spaces and localized abbreviation.
  11. ///
  12. /// - Parameter date: The past `Date` to calculate elapsed time from.
  13. /// - Returns: A formatted string like `"< 1 m"` or `"2 m"`. Returns `"--"` if the date is `nil`.
  14. static func minutesAgo(from date: Date?) -> String {
  15. guard let date = date else {
  16. return "--"
  17. }
  18. let secondsAgo = -date.timeIntervalSinceNow
  19. let minutesAgo = Int(floor(secondsAgo / 60))
  20. if minutesAgo >= 1 {
  21. let minuteString = Formatter.timaAgoFormatter.string(for: Double(minutesAgo)) ?? "\(minutesAgo)"
  22. return minuteString + "\u{00A0}" + String(localized: "m", comment: "Abbreviation for Minutes")
  23. } else {
  24. return "<" + "\u{00A0}" + "1" + "\u{00A0}" + String(localized: "m", comment: "Abbreviation for Minutes")
  25. }
  26. }
  27. // Calculates the floored integer value of how many full minutes ago the given date occurred.
  28. ///
  29. /// - Parameter date: The past `Date` to compare against the current time.
  30. /// - Returns: An integer representing the number of full minutes since the given date.
  31. /// Returns `Int.max` if the date is `nil`.
  32. static func minutesAgoValue(from date: Date?) -> Int {
  33. guard let date = date else {
  34. return Int.max
  35. }
  36. return Int(floor(-date.timeIntervalSinceNow / 60))
  37. }
  38. }