我想找到下一个小时的时间。 E.g。
现在是:4月9日,格林威治标准时间上午10:12:34 + 10 我想得到:4月9日,格林尼治标准时间11:00:00 + 10
所以我尝试使用Calendar.current.nextDate,但我得到了奇怪的回应。 示例代码如下。
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .short
dateFormatter.timeStyle = .long
var dateComponents = DateComponents()
dateComponents.minute = 0
dateComponents.second = 0
let beginDate = Date(timeIntervalSince1970: 0)
var beginDateComponents = Calendar.current.dateComponents(in: TimeZone.current, from: beginDate)
beginDateComponents.minute = 0
beginDateComponents.second = 0
let modifiedDate = Calendar.current.date(from: beginDateComponents)!
let nextHourlyTime = Calendar.current.nextDate(after: modifiedDate, matching: dateComponents, matchingPolicy: .nextTime)!
print("modifiedDate: \(dateFormatter.string(from: modifiedDate))")
print("beginDate: \(dateFormatter.string(from: beginDate))")
print("nextHourlyTime: \(dateFormatter.string(from: nextHourlyTime))")
/*
modifiedDate: 1/1/70, 10:00:00 AM GMT+10
beginDate: 1/1/70, 10:00:00 AM GMT+10
nextHourlyTime: 1/2/70, 12:00:00 AM GMT+10
*/
但如果我输入注释代码:" dateComponents.second = 0",那么我会得到正确答案。
Apple的nextDate api有什么问题吗?
答案 0 :(得分:5)
错误发生在您的beginDate。它应设置为Date()
而不是Date(timeIntervalSince1970: 0)
。你可以这样做:
extension Date {
var nextHourShift: Date? {
return Calendar.current.nextDate(after: self, matching: DateComponents(minute: 0), matchingPolicy: .nextTime)
}
}
Date().nextHourShift // "Sep 3, 2016, 4:00 AM"