TimeAgo 总是显示为“Just Now”
Posted
技术标签:
【中文标题】TimeAgo 总是显示为“Just Now”【英文标题】:TimeAgo Always appears as "Just Now" 【发布时间】:2021-02-15 08:07:28 【问题描述】:我似乎无法理解发生了什么,以及为什么当它应该改变时什么都没有改变
let date = Date(timeIntervalSince1970: timestamp)
let timeAgo = timeAgoSince(date)
print(timeAgo)
print (timeAgo) 总是显示为“Just Now” 关于这个问题我能得到任何帮助吗?
这是我的扩展
public func timeAgoSince(_ date: Date) -> String
let calendar = Calendar.current
let now = Date()
let unitFlags: NSCalendar.Unit = [.second, .minute, .hour, .day, .weekOfYear, .month, .year]
let components = (calendar as NSCalendar).components(unitFlags, from: date, to: now, options: [])
if let year = components.year, year >= 2
return "\(year) years ago"
if let year = components.year, year >= 1
return "Last year"
if let month = components.month, month >= 2
return "\(month) months ago"
if let month = components.month, month >= 1
return "Last month"
if let week = components.weekOfYear, week >= 2
return "\(week) weeks ago"
if let week = components.weekOfYear, week >= 1
return "Last week"
if let day = components.day, day >= 2
return "\(day) days ago"
if let day = components.day, day >= 1
return "Yesterday"
if let hour = components.hour, hour >= 2
return "\(hour) hours ago"
if let hour = components.hour, hour >= 1
return "An hour ago"
if let minute = components.minute, minute >= 2
return "\(minute) minutes ago"
if let minute = components.minute, minute >= 1
return "A minute ago"
if let second = components.second, second >= 3
return "\(second) seconds ago"
return "Just now"
Timestamp 的值为 1604189555939 但 timeago 并没有改变任何帮助?并感谢
【问题讨论】:
假设您的时间戳是过去的,它是自 1970 年以来的 毫秒... 不是打印timeAgo
do print(date)
,而是立即发现问题。并且不要在 Swift 中使用 NS...
的东西,有原生类型。
谢谢,我试试
【参考方案1】:
您的时间戳以毫秒为单位,而 Date(timeIntervalSince1970: timestamp) 需要几秒钟,因此使用以下代码将解决您的问题:
let date = Date(timeIntervalSince1970: timestamp / 1000)
let timeAgo = timeAgoSince(date)
print(timeAgo)
【讨论】:
以上是关于TimeAgo 总是显示为“Just Now”的主要内容,如果未能解决你的问题,请参考以下文章
****timeago.js插件:jquery实现几分钟前几小时前几天前等时间差显示效果的代码实例