Skip to content

Instantly share code, notes, and snippets.

@JulienKode
Created December 2, 2018 07:42
Show Gist options
  • Save JulienKode/7dfce01bdbf8aa5e61658a3e0f5bd441 to your computer and use it in GitHub Desktop.
Save JulienKode/7dfce01bdbf8aa5e61658a3e0f5bd441 to your computer and use it in GitHub Desktop.
Simple example to display Time ago from a Date in Swift
extension Date {
func timeAgoDisplay() -> String {
let calendar = Calendar.current
let minuteAgo = calendar.date(byAdding: .minute, value: -1, to: Date())!
let hourAgo = calendar.date(byAdding: .hour, value: -1, to: Date())!
let dayAgo = calendar.date(byAdding: .day, value: -1, to: Date())!
let weekAgo = calendar.date(byAdding: .day, value: -7, to: Date())!
if minuteAgo < self {
let diff = Calendar.current.dateComponents([.second], from: self, to: Date()).second ?? 0
return "\(diff) sec ago"
} else if hourAgo < self {
let diff = Calendar.current.dateComponents([.minute], from: self, to: Date()).minute ?? 0
return "\(diff) min ago"
} else if dayAgo < self {
let diff = Calendar.current.dateComponents([.hour], from: self, to: Date()).hour ?? 0
return "\(diff) hrs ago"
} else if weekAgo < self {
let diff = Calendar.current.dateComponents([.day], from: self, to: Date()).day ?? 0
return "\(diff) days ago"
}
let diff = Calendar.current.dateComponents([.weekOfYear], from: self, to: Date()).weekOfYear ?? 0
return "\(diff) weeks ago"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment