【问题标题】:Converting Timestamp from Firebase to Time Ago将时间戳从 Firebase 转换为 Time Ago
【发布时间】:2018-10-19 21:07:02
【问题描述】:

当用户点击提要中的帖子时,我想显示每条评论的发布时间。我正在尝试将 Date().timeIntervalSince1970 值转换为“x 时间前”的发布时间。

在视图加载之前,我为今天的日期声明一个 now 变量。

let now = Date()

日期是在我为 cmets 设置字典时分配的。

let commentValues: [String: Any] = [
        "comment" : comment,
        "uid": uid,
        "commentDate": Date().timeIntervalSince1970
    ]

我正在获取这样的 cmets,其中我还调用日期函数并将其分配给情节提要中的日期标签。

var comments = [Comment]()
fileprivate func fetchComments() {

    guard let postID = self.post?.id else {return}
    let commentRef = Database.database().reference().child("comments").child(postID)
    commentRef.observe(.childAdded, with: { (snapshot) in

        guard let dict = snapshot.value as? [String: Any] else {return}
        guard let comment = dict["comment"] as? String else {return}
        guard let uid = dict["uid"] as? String else {return}
        guard let commentDate = dict["commentDate"] as? Double else {return}


        let userRef = Database.database().reference().child("users/\(String(describing: uid))/profile")
        userRef.observe(.value, with: { snapshot in
            guard let value = snapshot.value as? [String:Any] else {return}
            let username = value["username"]
            let uid = dict["uid"]
            let email = value["email"]

            let myTimeInterval = TimeInterval(commentDate)
            let time = Date(timeIntervalSinceNow: myTimeInterval)

            let userProfile = User(uid: uid as! String, username: username as! String, email: email as! String)
            let comment = Comment(uid: uid as! String, user: userProfile, comment: comment, time: time.timeAgoDisplay())
            self.comments.append(comment)
            self.commentCollectionView.reloadData()
            })
        })
}

我已经设置了一个日期扩展,我正在尝试计算该日期的 timeAgo:

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
        let month = 4 * week
        let year = 12 * month

        if secondsAgo < minute  {
            print("\(secondsAgo)s ago")
            return "\(secondsAgo)s ago"
        } else if secondsAgo < hour {
            return "\(secondsAgo)m ago"
        } else if secondsAgo < day {
            return "\(secondsAgo)hr ago"
        } else if secondsAgo < week {
            return "\(secondsAgo)d ago"
        } else if secondsAgo < month {
            return "\(secondsAgo)w ago"
        } else if secondsAgo < year {
            return "\(secondsAgo)mo ago"
        }
        return "\(secondsAgo)yr ago"
}
}

正在显示日期,但我得到的结果是“-12983918 秒前”。如何将时间显示为“2s 前”或“1h 前”或“1w 前”等?

【问题讨论】:

  • 你可以使用calendar.component...有机会我会发布一个例子。干杯!

标签: ios swift firebase time timestamp


【解决方案1】:

这是一个使用 Calendar.component 来区分可能的时间结果的示例。

if let timestamp = post?.timestamp {
        print(timestamp)
        let timestampDate = Date(timeIntervalSince1970: Double(timestamp))
        let now = Date()
        let components = Set<Calendar.Component>([.second, .minute, .hour, .day, .weekOfMonth])
        let diff = Calendar.current.dateComponents(components, from: timestampDate, to: now)

        var timeText = ""
        if diff.second! <= 0 {
            timeText = "Now"
        }
        if diff.second! > 0 && diff.minute! == 0 {
            timeText = (diff.second == 1) ? "\(diff.second!) second ago" : "\(diff.second!) seconds ago"
        }
        if diff.minute! > 0 && diff.hour! == 0 {
            timeText = (diff.minute == 1) ? "\(diff.minute!) minute ago" : "\(diff.minute!) minutes ago"
        }
        if diff.hour! > 0 && diff.day! == 0 {
            timeText = (diff.hour == 1) ? "\(diff.hour!) hour ago" : "\(diff.hour!) hours ago"
        }
        if diff.day! > 0 && diff.weekOfMonth! == 0 {
            timeText = (diff.day == 1) ? "\(diff.day!) day ago" : "\(diff.day!) days ago"
        }
        if diff.weekOfMonth! > 0 {
            timeText = (diff.weekOfMonth == 1) ? "\(diff.weekOfMonth!) week ago" : "\(diff.weekOfMonth!) weeks ago"
        }

        timeLabel.text = timeText
    }

此示例附加了“帖子”的时间戳...但您可以对您的 cmets 使用相同的逻辑。试一试,如果您有任何问题,请告诉我。干杯!

编辑:包括 Calendar.component 上的文档 https://developer.apple.com/documentation/foundation/calendar.component

【讨论】:

【解决方案2】:

您需要将secondsAgo 转换为秒、日期、月份、年份……: 这是一个想法:

func timeAgoDisplay() -> String {
let secondsAgo = Int(Date().timeIntervalSince(self))
var result = ""
if secondsAgo >= 60 {
    let minutesAgo = secondsAgo / 60
    if minutesAgo >= 60 {
        let hoursAgo = minutesAgo / 60
        if hoursAgo >= 60 {
            let daysAgo = hoursAgo / 24
            if daysAgo >= 30 {
                let monthsAgo = daysAgo / 12
                if monthsAgo >= 12 {
                    let yearsAgo = monthsAgo / 12
                    result = "\(yearsAgo)y ago"
                } else { // months < 12
                    result = "\(monthsAgo)mo ago"
                }
            } else { // days < 30
                result = "\(daysAgo)d ago"
            }
        } else { // hours < 24
            result = "\(hoursAgo)h ago"
        }
    } else { // minutes < 60ms
        result =  "\(minutesAgo)m ago"
    }
} else { // seconds < 60s
    result = "\(secondsAgo)seconds ago"
}
return result
}

希望对你有帮助

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-29
    • 2013-10-22
    • 1970-01-01
    • 1970-01-01
    • 2018-12-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多