I'm trying to display "days: hours: min: sec" from a Date
in a UILabel
. I'm using this extension Date
from this answer here but it doesn't update the UILabel
I have. Not sure what I'm doing wrong. Here's my code:
extension Date {
func offsetFrom(date : Date) -> String {
let dayHourMinuteSecond: Set<Calendar.Component> = [.day, .hour, .minute, .second]
let now = Date()
let difference = NSCalendar.current.dateComponents(dayHourMinuteSecond, from: date, to: now)
let seconds = "\(difference.second ?? 0)s"
let minutes = "\(difference.minute ?? 0)m" + " " + seconds
let hours = "\(difference.hour ?? 0)h" + " " + minutes
let days = "\(difference.day ?? 0)d" + " " + hours
if let day = difference.day, day > 0 { return days }
if let hour = difference.hour, hour > 0 { return hours }
if let minute = difference.minute, minute > 0 { return minutes }
if let second = difference.second, second > 0 { return seconds }
return ""
}
}
// MARK: - Poll Expiration Date
if let expirationTimeInt = post?.pollExpirationTime {
let expirationDate = Date(timeIntervalSince1970: Double(expirationTimeInt))
print(expirationDate) // prints "2018-07-11 164:19:58 PM +0000"
pollExpirationDate.text = expirationDate.offsetFrom(date: expirationDate) // shows nothing
}