Skip to content

Instantly share code, notes, and snippets.

@katiesmillie
Created January 27, 2017 15:56
Show Gist options
  • Save katiesmillie/125e327553d7491fc8730f81d4d57030 to your computer and use it in GitHub Desktop.
Save katiesmillie/125e327553d7491fc8730f81d4d57030 to your computer and use it in GitHub Desktop.
Time Ago String Swift 3
extension: Date {
var timeAgoString: String {
let interval = Calendar.current.dateComponents([.year, .month, .day, .hour], from: self, to: Date())
if let year = interval.year, year > 0 {
return year == 1 ? "\(year) year ago" : "\(year) years ago"
} else if let month = interval.month, month > 0 {
return month == 1 ? "\(month) month ago" : "\(month) months ago"
} else if let day = interval.day, day > 0 {
return day == 1 ? "\(day) day ago" : "\(day) days ago"
} else if let hour = interval.hour, hour > 0 {
return hour == 1 ? "\(hour) hour ago" : "\(hour) hours ago"
} else {
return "a moment ago"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment