Created
January 27, 2017 15:56
-
-
Save katiesmillie/125e327553d7491fc8730f81d4d57030 to your computer and use it in GitHub Desktop.
Time Ago String Swift 3
This file contains 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 { | |
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