I have a number of dates that I am trying to represent using a relative date such as \"Today, Yesterday, 1 week ago, 1 month ago\" etc...
This is the Swift code I am usi
var relativeTime: String {
// don't forget spacing on these constants.
let futurePrefix = "" // " in" is a viable choice here...
let pastSuffix = " ago" // " ago" is a viable choice here...
let now = NSDate()
for (method, unitName) in [
(now.years, "year"),
(now.months, "month"),
(now.weeks, "week"),
(now.days, "day"),
(now.hours, "hour"),
(now.minutes, "minute"),
(now.seconds, "second")
] {
let qty = method(self)
let absQty = abs(method(self))
if absQty > 0 {
return (qty < 0 ? futurePrefix : "") +
String(absQty) + " " +
unitName +
(absQty == 1 ? "": "s") +
(qty > 0 ? pastSuffix : "")
}
}
return ""
}
An alternative implementation of Leo Dabus's implementation of relativeTime that does both future and past and is more succinct. (Swift2.3)