鉴于日期,我想在4:00收到日期。这在0:00 - 3:39失败:
let date3am = Calendar.current.date(from: DateComponents(year: 2017, month: 7, day: 1, hour: 3, minute: 0, second: 0))!
let date = Calendar.current.date(bySettingHour: 4, minute: 0, second: 0, of:
date3am, direction: .backward)!
date // "Jul 1, 2017, 4:00 AM"
date < date3am // false
为什么date(bySettingHour)
不会倒退?
答案 0 :(得分:2)
您使用的是错误的方法。您需要使用日历方法nextDate(after date:)
,如下所示:
let date3am = Calendar.current.date(from: DateComponents(year: 2017, month: 7, day: 1, hour: 3, minute: 0, second: 0))!
if let date = Calendar.current.nextDate(after: date3am, matching: DateComponents(hour: 4, minute: 0, second: 0), matchingPolicy: .nextTime, repeatedTimePolicy: .first, direction: .backward) {
date // "Jun 30, 2017, 4:00 AM"
date < date3am // true
}