Skip to content

Instantly share code, notes, and snippets.

@shanecowherd
Last active December 20, 2019 21:28
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 shanecowherd/f3baa5603be24ae2e39908206d1dcc5b to your computer and use it in GitHub Desktop.
Save shanecowherd/f3baa5603be24ae2e39908206d1dcc5b to your computer and use it in GitHub Desktop.
A modified version of timeAgo. The native Apple one has bugs in iOS 12-13
extension Date {
func timeAgoSinceDate() -> String {
// From Time
let fromDate = self
// To Time
let toDate = Date()
let time = Calendar.current.dateComponents([.month, .day, .hour, .minute, .second], from: fromDate, to: toDate)
guard let months = time.month else { return "" }
guard let days = time.day else { return "" }
guard let hours = time.hour else { return "" }
guard let minutes = time.minute else { return "" }
guard let seconds = time.second else { return "" }
if months > 0 {
return "\(months)mo \(days)d"
} else if days > 0 {
return "\(days)d \(hours)h"
} else if hours > 0 {
return "\(hours)h \(minutes)m"
} else if minutes > 0 {
return "\(minutes)m \(seconds)s"
} else {
return "\(seconds)s"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment