Skip to content

Instantly share code, notes, and snippets.

@Catherine-K-George
Created June 13, 2021 11:15
Show Gist options
  • Save Catherine-K-George/0a24bc56805bbd773dbb71900dc2ff99 to your computer and use it in GitHub Desktop.
Save Catherine-K-George/0a24bc56805bbd773dbb71900dc2ff99 to your computer and use it in GitHub Desktop.
Hours ago text for chat time labels + Swift
extension Date {
func differenceFromNow() -> DateComponents {
return Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: self, to: Date())
}
}
extension DateComponents {
func agoString() -> String {
if let year = year, year > 0 {
return "\(year) \(year > 1 ? "years" : "year") ago"
} else if let month = month, month > 0{
return "\(month) \(month > 1 ? "months" : "month") ago"
} else if let days = day, days > 0 {
if days > 7 {
let weeks: Int = days/7
return "\(weeks) \(weeks > 1 ? "weeks" : "week") ago"
}
return "\(days) \(days > 1 ? "days" : "day") ago"
} else if let hour = hour, hour > 0 {
return "\(hour) \(hour > 1 ? "hours" : "hour") ago"
} else if let minute = minute, minute > 0 {
return "\(minute) \(minute > 1 ? "minutes" : "minute") ago"
} else {
return "now"
}
}
}
@Catherine-K-George
Copy link
Author

usage example:

let string = "16:36 Wed, 13 Jun 2021"
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm E, d MMM y"
guard let oldDate = formatter.date(from: string) else { return }
print(oldDate.differenceFromNow().agoString())

Output sample:
12 minutes ago

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment