我使用的代码可以正常工作,但是我遇到了问题。例如,当分钟为02时,它表示2。我希望它为02。
@objc func tick() {
var calendar = Calendar(identifier: .iso8601)
calendar.timeZone = NSTimeZone.local
let currentDay = calendar.component(.day, from: Date())
let currentMonth = calendar.component(.month, from: Date())
let currentYear = calendar.component(.year, from: Date())
let currentHour = calendar.component(.hour, from: Date())
let currentHour1 = calendar.component(.minute, from: Date())
labelTimer.text = String (currentDay) + ("/") + String (currentMonth) + ("/") + String (currentYear) + ("/") + String (currentHour) + (":") + String (currentHour1)
}
答案 0 :(得分:2)
您的问题的解决方案是使用日期格式器,如下所示:
let formatter = DateFormatter()
formatter.dateFormat = "dd/MM/yyyy/HH:mm"
@objc func tick() {
labelTimer.text = formatter.string(from: Date())
}
注意:您可以简单地按所需方式更改字符串并获取另一个日期字符串。例如,将“ dd-MM-yyyy小时:HH分钟:mm”设置为有效