Skip to content

Instantly share code, notes, and snippets.

@manmal
Created July 22, 2019 11:45
Show Gist options
  • Save manmal/d1eed284ff8465cef686e9589724d41b to your computer and use it in GitHub Desktop.
Save manmal/d1eed284ff8465cef686e9589724d41b to your computer and use it in GitHub Desktop.
Date+TimeAgo.swift
extension Date {
var timeAgo: String {
let calendar = Calendar.current
let now = Date()
let earliest = self < now ? self : now
let latest = self > now ? self : now
let unitFlags: Set<Calendar.Component> = [.minute, .hour, .day, .weekOfMonth, .month, .year, .second]
let components: DateComponents = calendar.dateComponents(unitFlags, from: earliest, to: latest)
let year = components.year ?? 0
let month = components.month ?? 0
let weekOfMonth = components.weekOfMonth ?? 0
let day = components.day ?? 0
let hour = components.hour ?? 0
let minute = components.minute ?? 0
let second = components.second ?? 0
switch (year, month, weekOfMonth, day, hour, minute, second) {
case (let year, _, _, _, _, _, _) where year >= 2: return L10n.timeagoYears(year)
case (let year, _, _, _, _, _, _) where year == 1: return L10n.timeagoLastYear
case (_, let month, _, _, _, _, _) where month >= 2: return L10n.timeagoMonths(month)
case (_, let month, _, _, _, _, _) where month == 1: return L10n.timeagoLastMonth
case (_, _, let weekOfMonth, _, _, _, _) where weekOfMonth >= 2:
return L10n.timeagoWeeks(weekOfMonth)
case (_, _, let weekOfMonth, _, _, _, _) where weekOfMonth == 1: return L10n.timeagoLastWeek
case (_, _, _, let day, _, _, _) where day >= 2: return L10n.timeagoDays(day)
case (_, _, _, let day, _, _, _) where day == 1: return L10n.timeagoLastDay
case (_, _, _, _, let hour, _, _) where hour >= 2: return L10n.timeagoHours(hour)
case (_, _, _, _, let hour, _, _) where hour == 1: return L10n.timeagoLastHour
case (_, _, _, _, _, let minute, _) where minute >= 2: return L10n.timeagoMinutes(minute)
case (_, _, _, _, _, let minute, _) where minute == 1: return L10n.timeagoOneMinute
// case (_, _, _, _, _, _, let second) where second >= 3: return "\(second) seconds ago"
default: return L10n.timeagoJustNow
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment