我正在尝试以hh:mm:ss格式显示倒计时,但是由于我没有输出Date而是dateComponents,所以不能使用formatter.dateFormat。是否可以格式化dateComponents?
目前,我得到的输出看起来像这样:
时间:5,分钟:12,秒:45
func nextEventCalculator() -> DateComponents {
let now = Date()
let calendar = Calendar.current
let components = DateComponents(calendar: calendar, hour: 12, minute: 15) // <- 12:15 pm
let nextEvent = calendar.nextDate(after: now, matching: components, matchingPolicy: .nextTime)!
let diff = calendar.dateComponents([.hour, .minute, .second], from: now, to: nextEvent)
dateCountdownLabel.text = "\(diff)"
return diff
}
最佳答案
使用 DateComponentsFormatter
和unitsStyle
的 .positional
:
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
dateCountdownLabel.text = formatter.string(from: diff)
关于ios - 是否可以将dateComponent设置为hh:mm:ss格式?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/44476224/