Created
June 13, 2021 11:15
-
-
Save Catherine-K-George/0a24bc56805bbd773dbb71900dc2ff99 to your computer and use it in GitHub Desktop.
Hours ago text for chat time labels + Swift
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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" | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
usage example:
Output sample:
12 minutes ago