Skip to content

Instantly share code, notes, and snippets.

@streetturtle
Last active December 24, 2021 02:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save streetturtle/cbc809c80dcecfa55410942d418e9add to your computer and use it in GitHub Desktop.
Save streetturtle/cbc809c80dcecfa55410942d418e9add to your computer and use it in GitHub Desktop.
Date Extensions
extension Date {
func getElapsedInterval() -> String {
let interval = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: self, to: Date())
if let year = interval.year, year > 0 {
return "\(year) year\(year == 1 ? "" : "s") ago"
} else if let month = interval.month, month > 0 {
return "\(month) month\(month == 1 ? "" : "s") ago"
} else if let day = interval.day, day > 0 {
return "\(day) day\(day == 1 ? "" : "s") ago"
} else if let hour = interval.hour, hour > 0 {
return "\(hour) hour\(hour == 1 ? "" : "s") ago"
} else if let minute = interval.minute, minute > 0 {
return "\(minute) minute\(minute == 1 ? "" : "s") ago"
} else if let second = interval.second, second > 0 {
return "\(second) second\(second == 1 ? "" : "s") ago"
} else {
return "a moment ago"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment