将时间戳从Firebase转换为Time Ago

时间:2018-05-09 17:03:16

标签: ios swift firebase time timestamp

当用户点击Feed中的帖子时,我想显示每条评论的发布时间。我试图将Date()。timeIntervalSince1970值转换为“x time ago”,以便发布它。

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

let now = Date()

我为像这样的评论设置词典时分配了日期。

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

我正在获取这样的评论,我也称之为日期函数并将其分配给storyboard中的日期标签。

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"
}
}

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

2 个答案:

答案 0 :(得分: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
    }

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

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

答案 1 :(得分:0)

您需要将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
}

希望这有用