做电商的会遇到秒杀的活动,然后会有倒计时开始抢购的需求,写了个demo来解决这个需求,超级简单的,思路就是获取了当前的时间,和将来的时间点算出相差的天.时.分.秒,然后使用定时器进行倒计时,计算差的时候使用了Calendar来计算. Calendar的时间格式方法和OC的差距挺大,着实是个坑......
//随意设置一个将来的时间
let aaa : String = "2017.05.24 14:11:11"
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
//结束时间
let endDate = dateFormatter.date(from: aaa)
//当前时间
let currentDate = Date.init()
let calendar = Calendar.current
let unit:Set<Calendar.Component> = [.day,.hour,.minute,.second]
let commponent:DateComponents = calendar.dateComponents(unit, from: currentDate, to: endDate!)
print(commponent.day as Any,commponent.hour as Any,commponent.minute as Any,commponent.second as Any)
secondStr = commponent.second
minitStr = commponent.minute
hourStr = commponent.hour
dayStr = commponent.day
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(timerAction), userInfo: nil, repeats: true)
RunLoop.main.add(timer!, forMode: RunLoopMode.commonModes)
定时器的方法:
func timerAction() {
secondStr = secondStr! - 1
if secondStr == -1 {
secondStr = 59
minitStr = minitStr! - 1
if minitStr == -1 {
minitStr = 59
hourStr = hourStr! - 1
if hourStr == -1 {
hourStr = 23
dayStr = dayStr! - 1
}
}
}
if secondStr == 0 && minitStr! == 0 && hourStr == 0 && dayStr == 0 {
self.timer?.invalidate()
timer = nil
}
print(dayStr as Any,hourStr as Any,minitStr as Any,secondStr as Any)
}