Skip to content

Instantly share code, notes, and snippets.

@theevo
Created May 9, 2020 17:38
Show Gist options
  • Select an option

  • Save theevo/997aabc1dba37c2f24eb2cf477a81822 to your computer and use it in GitHub Desktop.

Select an option

Save theevo/997aabc1dba37c2f24eb2cf477a81822 to your computer and use it in GitHub Desktop.
import Foundation
extension Date {
func timeAgoString() -> String {
let units = Array<Calendar.Component>([.year, .month, .day, .hour, .minute, .second])
let components = Calendar.current.dateComponents(Set(units), from: self, to: Date())
for unit in units
{
guard let value = components.value(for: unit) else {
continue
}
if value == 1 {
return "\(value) \(unit) ago"
} else if value > 1 {
return "\(value) \(unit)s ago"
}
}
return "some time ago"
}
}
let date: Date! = DateComponents(calendar: Calendar.current, year: 2020, month: 5, day: 9, hour: 9, minute: 55).date
print(date.timeAgoString())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment