[英]How to compare between two dates and make timer countdown between them in swift 4
我試圖在未來日期和當前日期之間倒計時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秒
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.