是否可以格式化日期组件以显示为hh:mm:ss



我正在尝试以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.positionalDateComponentsFormatter

let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
dateCountdownLabel.text = formatter.string(from: diff)

相关内容

  • 没有找到相关文章

最新更新