我正在尝试以hh:mm:ss格式显示倒计时,但由于我不输出日期而是日期组件,所以我无法使用formatter.dateFormat。是否可以格式化日期组件?
目前我得到的输出如下所示:
小时: 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
}
使用unitsStyle
为 .positional
的 DateComponentsFormatter
:
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
dateCountdownLabel.text = formatter.string(from: diff)