一尘不染

从日期(NSDate)开始快速显示时间

swift

在一个单元格中,我想显示来自解析服务器中NSDate的时间。这是代码,但无法正常工作。一切都没有改变,数据也没有被解析。

    if let createdat = (object?["createdAt"] as? String){
            let pastDate = Date(timeIntervalSinceNow: TimeInterval(createdat)!)
            cell.TimeAgo.text = pastDate.timeAgoDisplay()
        }


       extension Date {
          func timeAgoDisplay() -> String {
        let secondsAgo = Int(Date().timeIntervalSince(self))

        let minute = 60
        let hour = 60 * minute
        let day = 24 * hour
        let week = 7 * day

        if secondsAgo < minute {
            return "\(secondsAgo) sec ago"
        } else if secondsAgo < hour {
            return "\(secondsAgo / minute) min ago"
        } else if secondsAgo < day {
            return "\(secondsAgo / hour) hrs ago"
        } else if secondsAgo < week {
            return "\(secondsAgo / day) days ago"
        }

        return "\(secondsAgo / week) weeks ago"
    }
}

阅读 265

收藏
2020-07-07

共1个答案

一尘不染

如果您只想要日期的Time Ago扩展名,请转到答案的底部😊

我将向您展示一个示例,让您在几秒钟前和之后展示您的扩展程序。

注意:如果需要,您可以直接使用Pase中的日期:

if let pastDate = (object?["createdAt"] as? Date) {
    cell.TimeAgo.text = pastDate.timeAgoDisplay()
}

迅捷5.1

示例如何在 Swift 5.1 之前显示秒数:

自iOS13以来,Apple引入了新类RelativeDateTimeFormatter

extension Date {
    func timeAgoDisplay() -> String {
        let formatter = RelativeDateTimeFormatter()
        formatter.unitsStyle = .full
        return formatter.localizedString(for: self, relativeTo: Date())
    }
}

此类将使您能够根据您的语言获取时间字符串。它会根据您的时间间隔自动选择正确的时间单位,下面是一个示例:

|--------------------------|------------------|
| Time interval in seconds |      Display     |
|--------------------------|------------------|
|             -6           |   6 seconds ago  |
|            -60           |   1 minute ago   |
|           -600           |  10 minutes ago  |
|          -6000           |    1 hour ago    |
|         -60000           |   16 hours ago   |
|--------------------------|------------------|

您会注意到它会自动为您处理复数形式。

Swift 3Swift 4

示例如何使用 Swift 3Swift 4 在几秒钟前获得提示:

首先:要获得秒数,我们需要检查是否有1分钟或更短的时间,要使当前日期减去1分钟,您可以这样写:

let minuteAgo = calendar.date(byAdding: .minute, value: -1, to: Date())!

第二:现在比较两个日期!(对于您的扩展名,我们将自己替换yourDate),并获得这两个日期之间的差额。

if (minuteAgo < yourDate) {
    let diff = Calendar.current.dateComponents([.second], from: yourDate, to: Date()).second ?? 0
    print("\(diff) sec ago")
}

仅此而已,现在您可以打印时间了!

因此,您的扩展名是这样的:(这是获得时间之前的一个简单扩展名)

extension Date {
    func timeAgoDisplay() -> String {

        let calendar = Calendar.current
        let minuteAgo = calendar.date(byAdding: .minute, value: -1, to: Date())!
        let hourAgo = calendar.date(byAdding: .hour, value: -1, to: Date())!
        let dayAgo = calendar.date(byAdding: .day, value: -1, to: Date())!
        let weekAgo = calendar.date(byAdding: .day, value: -7, to: Date())!

        if minuteAgo < self {
            let diff = Calendar.current.dateComponents([.second], from: self, to: Date()).second ?? 0
            return "\(diff) sec ago"
        } else if hourAgo < self {
            let diff = Calendar.current.dateComponents([.minute], from: self, to: Date()).minute ?? 0
            return "\(diff) min ago"
        } else if dayAgo < self {
            let diff = Calendar.current.dateComponents([.hour], from: self, to: Date()).hour ?? 0
            return "\(diff) hrs ago"
        } else if weekAgo < self {
            let diff = Calendar.current.dateComponents([.day], from: self, to: Date()).day ?? 0
            return "\(diff) days ago"
        }
        let diff = Calendar.current.dateComponents([.weekOfYear], from: self, to: Date()).weekOfYear ?? 0
        return "\(diff) weeks ago"
    }
}

要使用它,这非常简单:

var now = Date()
now.timeAgoDisplay()
2020-07-07