2016-12-04 83 views
1

我需要显示一天中的时间(例如,14:02)并将其显示在UILable中。按下按钮时的一天的显示时间ios

这里是我的代码来检索系统时间:

let date = Date() 
let calendar = Calendar.current 
let components = calendar.dateComponents([.hour, .minute, .second, .nanosecond], from: date) 
_ = components.hour 

我无法弄清楚如何将其提供给标签。

mylable.text = "???" 

谢谢。

回答

2

您需要使用DateFormatter而不是DateComponents以获得特定格式的DateTime

let dateFormatter = DateFormatter() 
dateFormatter.dateFormat = "HH:mm" 
let time = dateFormatter.string(from: Date()) 
mylable.text = time 
+0

谢谢。它完美的工作! –

+0

@AntonPlatonov欢迎队友:) –

+0

还有一个小问题。我不能将它集成到按钮函数中,因为它只能在super.ViewDidLoad中使用。我试图创建一个布尔值并在super.ViewDidLoad中使用if语句...没有用... UPD:我将整个代码块放在按钮中,并且它工作正常。再次感谢 –

相关问题