我有一個包含實時時間的標簽。我的問題是如何將標簽的時間與下午 4:00 進行比較。我需要知道標簽時間是小于還是大于下午 4:00。
我的viewDidLoad:
override func viewDidLoad() {
labelTiempo.text = DateFormatter.localizedString(from: Date(), dateStyle: .none, timeStyle: .short)
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(self.tick) , userInfo: nil, repeats: true)
labelFuncion.text = "Funcion: " filme!.funcion!
}
//complement function
@objc func tick() {
labelTiempo.text = DateFormatter.localizedString(from: Date(), dateStyle: .none,timeStyle: .short)
}
[包含標簽的視圖的螢屏截圖。][1] [1]:https://i.stack.imgur.com/bIVxG.png
uj5u.com熱心網友回復:
不要使用標簽來保存資訊。
將您設定標簽文本時的日期保存為Date模型(或簡單地作為視圖控制器中的屬性。然后,當您需要告訴“標簽時間”是否在下午 4:00 之前或之后,使用 Calendar 方法date(bySettingHour:minute:second:of:matchingPolicy:repeatedTimePolicy:direction:)生成當地時間下午 4:00 的日期,然后簡單地比較它們。
class MyViewController: UIViewController {
var startTime: Date!
// Your other instance variables go here
override func viewDidLoad() {
startTime = Date()
labelTiempo.text = DateFormatter.localizedString(from: startTime, dateStyle: .none, timeStyle: .short)
timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector:#selector(self.tick) , userInfo: nil, repeats: true)
labelFuncion.text = "Funcion: " filme!.funcion!
}
// Your view controller's other functions go here
}
判斷“標簽時間”是在 4:00 之前還是之后的代碼:
let fourOClockToday = Calendar.current.date(bySettingHour: 16, minute: 0,second: 0 of: startTime)
if startTime < fourOClockToday {
print("The 'labelTime' is after 4:00 PM")
} else {
print("The 'labelTime' is ≤ 4:00 PM")
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/477701.html
上一篇:iOSdiffindaysusingdateComponent(_:from:to:)-nil對結果日意味著什么?
