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()总结
以上是内存溢出为你收集整理的ios – 从日期开始显示Swift时间(NSDate)全部内容,希望文章能够帮你解决ios – 从日期开始显示Swift时间(NSDate)所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)