Swift iOS doesRelativeDateFormatting have different values besides “Today” and “Yesterday”?

后端 未结 4 1843
长发绾君心
长发绾君心 2021-02-12 21:17

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

4条回答
  •  南方客
    南方客 (楼主)
    2021-02-12 21:52

    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)

提交回复
热议问题