ios – 从日期开始显示Swift时间(NSDate)

前端之家收集整理的这篇文章主要介绍了ios – 从日期开始显示Swift时间(NSDate)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
在一个单元格中,我想在Parse服务器中显示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"
    }
}

解决方法

If you just want a Time Ago extension for Date go to the bottom of the answer ?

我会告诉你一个例子,只是为了几秒钟之前,我会更新你的扩展程序.

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

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

示例如何使用Swift 3或Swift 4获取秒数:

第一:要获得秒数,我们需要检查是否有一分钟或更短时间,要获得当前日期减去一分钟,您可以写下:

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

第二:现在比较两个日期! (如果你的扩展我们自己替换你的日期)并获得这2个日期之间的差异.

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,to: Date())!
        let hourAgo = calendar.date(byAdding: .hour,to: Date())!
        let dayAgo = calendar.date(byAdding: .day,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],to: Date()).minute ?? 0
            return "\(diff) min ago"
        } else if dayAgo < self {
            let diff = Calendar.current.dateComponents([.hour],to: Date()).hour ?? 0
            return "\(diff) hrs ago"
        } else if weekAgo < self {
            let diff = Calendar.current.dateComponents([.day],to: Date()).day ?? 0
            return "\(diff) days ago"
        }
        let diff = Calendar.current.dateComponents([.weekOfYear],to: Date()).weekOfYear ?? 0
        return "\(diff) weeks ago"
    }
}

要使用它,这非常简单:

var now = Date()
now.timeAgoDisplay()
原文链接:https://www.f2er.com/iOS/328002.html

猜你在找的iOS相关文章