我正在创建一个倒数计时器,显示小时:分钟:秒。
我所使用的功能,如果数字小于10,它会将值返回为1位数。(例如2:3:15)
如何格式化我的功能以便始终有两位数?
我正在寻找如下结果:02:03:15
func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
答案 0 :(得分:0)
或者使用DateComponentsFormatter
lazy var dateComponentsFormatter: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.zeroFormattingBehavior = .pad
formatter.allowedUnits = [.hour, .minute, .second]
return formatter
}()
func secondsToHoursMinutesSeconds(seconds: Int) -> String {
let hourPad = seconds < 36000 ? "0" : "" // add 0 in front if less than 10 hours
return hourPad + dateComponentsFormatter.string(from: seconds)!
}
secondsToHoursMinutesSeconds(3602) // 01:00:02
由于DateComponentsFormatter
不会自动使用zeroFormattingBehavior = .pad
填充小时数,因此您必须手动添加&#34;&#34;。
格式化程序本身被声明为惰性计算属性,以避免重复重新实例化。