john john -4 years ago 131
iOS Question

Swift time ago from Parse createdAt date

In a cell I want to display the time ago from the NSDate in the Parse server. Here is the code but its not working. Nothing is changing, and the data isn't being parsed.

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download