我有以下代码
var calendar = Calendar.current
let unitFlags = Set<Calendar.Component>([.hour, .year, .minute])
calendar.timeZone = TimeZone(identifier: "UTC")!
let startHour = calendar.component(.hour, from: cell.startDate as Date)
let startMinutes = calendar.component(.minute, from: cell.endDate as Date)
let endHour = calendar.component(.hour, from: cell.endDate as Date)
let endMinute = calendar.component(.minute, from: cell.endDate as Date)
print("start hours = \(startHour) : \(startMinutes)")
print("end hours = \(endHour) : \(endMinute)")
所以,结果是正确的,但格式错误。例如,它打印22:30,这是我想要的,但是当涉及到小于10的数字时,例如2 AM,它打印2:0而不是02:00。我怎么解决这个问题?我试图将dateformatter链接到日历,但我不能。我也尝试采用以下方法解决这个问题:
let myFormatter = DateFormatter()
myFormatter.dateFormat = "HH:mm"
print(myFormatter.string(from: cell.startDate))
print(myFormatter.string(from: cell.endDate))
但是打印时间与确切的小时数无关。不知道为什么。
所以,非常感谢任何帮助!
答案 0 :(得分:1)
有多种方法可以添加缺少的前导零,但最好的解决方案是使用DateFormatter
。格式化程序只有一个问题 - 设置正确的时区。
// safer than using identifiers that are not actually standardised
myFormatter.timeZone = TimeZone(secondsFromGMT: 0)