是否可以格式化dateComponent以显示为hh:mm:ss?

时间:2017-06-10 17:38:25

标签: ios swift date time nsdate

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

1 个答案:

答案 0 :(得分:2)

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

一起使用
^[^-]([a-zA-z-]*)[^-]$