如何从swift的剩余时间开始coutdown时间?

时间:2016-08-10 13:00:18

标签: swift nsdate nstimer countdown nstimeinterval

我有剩余的时间用“dd HH:mm:ss”格式,我必须从中运行倒计时时间。我正在使用此代码

func updateCounter() {
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "dd HH:mm:ss"
    let date = dateFormatter.dateFromString(timerString)
    let timeLeft = date!.timeIntervalSinceReferenceDate
    lblTImer.text = timeLeft.time
    lblTImer.font = UIFont.init(name: "Gotham-Book", size: 20)
}

用于更新标签

extension NSTimeInterval {
    var time:String {
        return String(format:"%02d : %02d : %02d : %02d", Int((self/86400)), Int((self/3600.0)%24), Int((self/60.0)%60), Int((self)%60))
    }

}

但我没有得到正确的时间,纠正我的错误。

1 个答案:

答案 0 :(得分:0)

因为您错误地使用了NSDateFormatter。例如,timerString中没有年份和月份,只有小时,分钟,秒。另一方面,你忘了调整时区。

您的timeString表示持续时间,以秒为单位,格式为day hour:minute:second样式。据我所知,Cocoa / UITouch没有为此提供合适的格式化程序。但建立一个很简单:

extension NSTimeInterval {
    init(fromString str: String) {
        let units: [Double] = [1, 60, 3600, 86400]
        let components = str.componentsSeparatedByCharactersInSet(NSCharacterSet(charactersInString: " :")).reverse()

        self = zip(units, components)
                .map { $0 * (Double($1) ?? 0) }
                .reduce(0, combine: +)
    }

    var time:String {
        return String(format:"%02d : %02d : %02d : %02d", Int((self/86400)), Int((self/3600.0)%24), Int((self/60.0)%60), Int((self)%60))
    }
}


let timerString = "1 22:26:20"

let timeLeft = NSTimeInterval(fromString: "1 22:26:20")
print(timeLeft)         // 167180.0
print(timeLeft.time)    // 01 : 22 : 26 : 20
相关问题