Skip to content

Instantly share code, notes, and snippets.

@shanecowherd

shanecowherd/timeago.swift

Last active Dec 20, 2019
Embed
What would you like to do?
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
You can’t perform that action at this time.