I want to convert nsdate in to relative format like \"Today\",\"Yesterday\",\"a week ago\",\"a month ago\",\"a year ago\",\"date as it is\".
I have writ
FOR: SWIFT 3
Here's a Swift 3 version, for past dates, that handles all units and singular or plural in the returned String.
Example Use:
let oneWeekAgo = Calendar.current.date(byAdding: .weekOfYear, value: -1, to: Date())!
print(relativePast(for: oneWeekAgo)) // output: "1 week ago"
I based it on a riff off of Saurabh Yadav's. Thanks.
func relativePast(for date : Date) -> String {
let units = Set([.year, .month, .day, .hour, .minute, .second, .weekOfYear])
let components = Calendar.current.dateComponents(units, from: date, to: Date())
if components.year! > 0 {
return "\(components.year!) " + (components.year! > 1 ? "years ago" : "year ago")
} else if components.month! > 0 {
return "\(components.month!) " + (components.month! > 1 ? "months ago" : "month ago")
} else if components.weekOfYear! > 0 {
return "\(components.weekOfYear!) " + (components.weekOfYear! > 1 ? "weeks ago" : "week ago")
} else if (components.day! > 0) {
return (components.day! > 1 ? "\(components.day!) days ago" : "Yesterday")
} else if components.hour! > 0 {
return "\(components.hour!) " + (components.hour! > 1 ? "hours ago" : "hour ago")
} else if components.minute! > 0 {
return "\(components.minute!) " + (components.minute! > 1 ? "minutes ago" : "minute ago")
} else {
return "\(components.second!) " + (components.second! > 1 ? "seconds ago" : "second ago")
}
}