19

我有许多日期,我试图使用相对日期来表示,例如“今天、昨天、1 周前、1 个月前”等...

这是我正在使用的 Swift 代码:

let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .MediumStyle
dateFormatter.doesRelativeDateFormatting = true
let uploadDate = dateFormatter.stringFromDate(date)

仅表示“今天”和“昨天”,其余日期如下所示:2014 年 11 月 24 日 2014 年 11 月 17 日等...

是否有另一种方法可以使用相对日期而不是实际日期来表示所有日期?

4

4 回答 4

26

编辑/更新:Xcode 8.3.2 • Swift 3.1

如果您使用扩展和日历方法来帮助您进行日历计算,这真的很容易:

extension Date {
    var yearsFromNow: Int {
        return Calendar.current.dateComponents([.year], from: self, to: Date()).year!
    }
    var monthsFromNow: Int {
        return Calendar.current.dateComponents([.month], from: self, to: Date()).month!
    }
    var weeksFromNow: Int {
        return Calendar.current.dateComponents([.weekOfYear], from: self, to: Date()).weekOfYear!
    }
    var daysFromNow: Int {
        return Calendar.current.dateComponents([.day], from: self, to: Date()).day!
    }
    var isInYesterday: Bool {
        return Calendar.current.isDateInYesterday(self)
    }
    var hoursFromNow: Int {
        return Calendar.current.dateComponents([.hour], from: self, to: Date()).hour!
    }
    var minutesFromNow: Int {
        return Calendar.current.dateComponents([.minute], from: self, to: Date()).minute!
    }
    var secondsFromNow: Int {
        return Calendar.current.dateComponents([.second], from: self, to: Date()).second!
    }
    var relativeTime: String {
        if yearsFromNow > 0 { return "\(yearsFromNow) year" + (yearsFromNow > 1 ? "s" : "") + " ago" }
        if monthsFromNow > 0 { return "\(monthsFromNow) month" + (monthsFromNow > 1 ? "s" : "") + " ago" }
        if weeksFromNow > 0 { return "\(weeksFromNow) week" + (weeksFromNow > 1 ? "s" : "") + " ago" }
        if isInYesterday { return "Yesterday" }
        if daysFromNow > 0 { return "\(daysFromNow) day" + (daysFromNow > 1 ? "s" : "") + " ago" }
        if hoursFromNow > 0 { return "\(hoursFromNow) hour" + (hoursFromNow > 1 ? "s" : "") + " ago" }
        if minutesFromNow > 0 { return "\(minutesFromNow) minute" + (minutesFromNow > 1 ? "s" : "") + " ago" }
        if secondsFromNow > 0 { return secondsFromNow < 15 ? "Just now"
            : "\(secondsFromNow) second" + (secondsFromNow > 1 ? "s" : "") + " ago" }
        return ""
    }
}

测试

let calendar =  Calendar.current

let date1 = DateComponents(calendar: calendar, year: 2016, month:  3, day: 14, hour: 22, minute: 39).date!
let date2 = DateComponents(calendar: calendar, year: 2019, month:  4, day: 18, hour: 22, minute: 39).date!
let date3 = DateComponents(calendar: calendar, year: 2019, month: 6, day:  2, hour: 12, minute: 38).date!
let date4 = DateComponents(calendar: calendar, year: 2019, month: 6, day:  14, hour: 3, minute: 0).date!
let date5 = DateComponents(calendar: calendar, year: 2019, month: 6, day:  17, hour: 23, minute: 45).date!
let date6 = DateComponents(calendar: calendar, year: 2019, month: 6, day:  18, hour: 19, minute:  17).date!
let timeOffset1 = date1.relativeTime // "3 years ago"
let timeOffset2 = date2.relativeTime // "1 month ago"
let timeOffset3 = date3.relativeTime // "2 weeks ago"
let timeOffset4 = date4.relativeTime // "4 days ago"
let timeOffset5 = date5.relativeTime // "Yesterday"
let timeOffset6 = date6.relativeTime // "Just now"
于 2014-12-06T23:54:37.257 回答
6

iOS 13+ 现在有RelativeDateFormatter

例如:https ://nshipster.com/formatter/#relativedatetimeformatter

let formatter = RelativeDateTimeFormatter()
formatter.localizedString(from: DateComponents(day: 1, hour: 1)) // "in 1 day"
formatter.localizedString(from: DateComponents(day: -1)) // "1 day ago"

或者

formatter.localizedString(for: date, relativeTo: Date())
于 2020-01-22T01:29:44.647 回答
5

你应该看看关于 NSDateComponentsFormatter 的 Mattt Thompsons 博客文章

http://nshipster.com/nsdatecomponents/http://nshipster.com/nsformatter/

let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Full

let components = NSDateComponents()
components.day = 1
components.hour = 2

let string = formatter.stringFromDateComponents(components)
// 1 day, 2 hours

示例(马特汤普森)

于 2014-12-06T23:49:21.077 回答
0
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 ""
}

Leo Dabus 的 relativeTime 实现的替代实现,它同时处理未来和过去,并且更简洁。(斯威夫特2.3)

于 2017-01-13T23:08:19.497 回答