从日期开始显示天:小时:分钟:秒

时间:2018-07-07 09:53:37

标签: ios swift date uilabel

我正在尝试在Date中的UILabel中显示“天:小时:分:秒”。我正在此答案here中使用此extension Date,但它不会更新我拥有的UILabel。不知道我在做什么错。这是我的代码:

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

        }

1 个答案:

答案 0 :(得分:3)

有一个更方便的API:DateComponentsFormatter

extension Date {

    func offsetFromNow() -> String {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.day, .hour, .minute, .second]
        formatter.unitsStyle = .abbreviated
        return formatter.string(from: Date(), to: self)!
    }
}

let date = Date().addingTimeInterval(100000)

print(date.offsetFromNow())