In Swift5, we have RelativeDateTimeFormatter
Prior to Swift5:
I\'m trying to convert time to time ago, what i wanna do is:
from 1
Swift 4 version of truongky's code:
And Add Optional for TimeEnd not now.
extension Date {
func getElapsedInterval(to end: Date = Date()) -> String {
if let interval = Calendar.current.dateComponents([Calendar.Component.year], from: self, to: end).day {
if interval > 0 {
return "\(interval) year\(interval == 1 ? "":"s")"
}
}
if let interval = Calendar.current.dateComponents([Calendar.Component.month], from: self, to: end).month {
if interval > 0 {
return "\(interval) month\(interval == 1 ? "":"s")"
}
}
if let interval = Calendar.current.dateComponents([Calendar.Component.weekOfMonth], from: self, to: end).weekOfMonth {
if interval > 0 {
return "\(interval) week\(interval == 1 ? "":"s")"
}
}
if let interval = Calendar.current.dateComponents([Calendar.Component.day], from: self, to: end).day {
if interval > 0 {
return "\(interval) day\(interval == 1 ? "":"s")"
}
}
if let interval = Calendar.current.dateComponents([Calendar.Component.hour], from: self, to: end).hour {
if interval > 0 {
return "\(interval) hour\(interval == 1 ? "":"s")"
}
}
if let interval = Calendar.current.dateComponents([Calendar.Component.minute], from: self, to: end).minute {
if interval > 0 {
return "\(interval) minute\(interval == 1 ? "":"s")"
}
}
return "Just now."
}
}