使用此代码,您可以节省当前时间但是如果分钟< 9比它给你5:9而不是5:09的时间。你怎么解决这个问题?
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let Tijd = "\(hour) : \(minutes)"
答案 0 :(得分:3)
你有两个选择。
使用String(format:)
let date = Date()
let calendar = Calendar.current
let hour = calendar.component(.hour, from: date)
let minutes = calendar.component(.minute, from: date)
let tijd = String(format:"%d:%02d", hour, minutes) // change to "%02d:%02d" if you also want the hour to be 2-digits.
使用DateFormatter
。
let date = Date()
let df = DateFormatter()
df.dateFormat = "H:mm" // Use "HH:mm" if you also what the hour to be 2-digits
let tijd = df.string(from: date)