我正在尝试NSTimer
在未来日期和当前日期之间进行倒计时,并且此更新出现在视图中。
例如,如果当前日期是 25/4/2019 而未来日期将是 30/4/2019,这将是一个倒数计时器 5d:2h:50m:20s
我用了一些代码
@IBOutlet weak var btnTimeLabel : UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let when = DispatchTime.now() + 0.1 // change 2 to desired number of seconds
DispatchQueue.main.asyncAfter(deadline: when) {
Timer.scheduledTimer(timeInterval: 0.1, target: self, selector: #selector(ViewController.countDownDate), userInfo: nil, repeats: true)
}
}
@objc func countDownDate() {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "dd-mm-yyyy" //Your date format
dateFormatter.timeZone = TimeZone(abbreviation: "GMT+0:00") //Current time zone
let futuredate = dateFormatter.date(from: "29-4-2019") //according to date format your date string
var calendar = Calendar.current
let diffDateComponents = calendar.dateComponents([.day, .hour, .minute, .second], from: Date(), to: futuredate!)
print (Date())
print(diffDateComponents)
let countdown = "Days \(String(describing:diffDateComponents.day!)), Hours: \(String(describing: diffDateComponents.hour!)), Minutes: \(String(describing: diffDateComponents.minute!)), Seconds: \(String(describing: diffDateComponents.second!))"
print("countdown",countdown)
var dayText = String(describing: diffDateComponents.day!) + "d "
var hourText = String(describing: diffDateComponents.hour!) + "h "
btnTimeLabel.setTitle(dayText + hourText + String(describing: diffDateComponents.minute!) + "m " + String(describing: diffDateComponents.second!) + "s", for: .normal)
//print(dayText + hourText + String(describing: diffDateComponents.minute!) + "m " + String(describing: diffDateComponents.second!) + "s")
} // Dispose of any resources that can be recreated.
}
它给了我错误的计时器
这是我使用DateComponentsFormatter获取时差的版本
设置DateComponentsFormatter
let dcf = DateComponentsFormatter()
dcf.allowedUnits = [.day, .hour, .minute, .second]
dcf.unitsStyle = .full
设置普通日期格式化程序
let df = ISO8601DateFormatter()
df.formatOptions = [.withFullDate, .withDashSeparatorInDate]
执行格式化
if let future = df.date(from: "2019-04-29"), let diff = dcf.string(from: Date(), to: future) {
print(diff)
}
输出是
3天6小时9分9秒
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句