我正在尝试构建一个[Date]
数组,该数组表示给定一天中的每一分钟。这就是我想到的,但我想知道是否有更有效的方法来实现这一点?
let calendar = Calendar.current
var arrayOfDaysMinutes: [Date] = []
var midnight = calendar.startOfDay(for: Date())
if let endOfDayDate = calendar.date(bySettingHour: 23, minute: 59, second: 59, of: midnight) {
print("midnight = (midnight) and one second before midnight = (endOfDayDate)")
for i in 0...1440 {
print("i = (i)")
let nextMinute = midnight.addingTimeInterval(60 * Double(i))
arrayOfDaysMinutes.append(nextMinute)
}
print("arrayOfDaysMinutes count = (arrayOfDaysMinutes.count)")
for minute in arrayOfDaysMinutes {
print("minute = (minute)")
}
}
请注意,并非每天都有24小时。它可能也有23或25个。关于最有效的方法,我认为使用DateComponentes日期属性比添加分钟或获取日期后的下一个日期快得多:
extension Date {
func year(using calendar: Calendar = .current) -> Int {
calendar.component(.year, from: self)
}
func month(using calendar: Calendar = .current) -> Int {
calendar.component(.month, from: self)
}
func day(using calendar: Calendar = .current) -> Int {
calendar.component(.day, from: self)
}
func noon(using calendar: Calendar = .current) -> Date {
calendar.date(bySettingHour: 12, minute: 0, second: 0, of: self)!
}
func startOfDay(using calendar: Calendar = .current) -> Date {
calendar.startOfDay(for: self)
}
func dayAfter(using calendar: Calendar = .current) -> Date {
calendar.date(byAdding: .day, value: 1, to: noon(using: calendar))!
}
func startOfNextDay(using calendar: Calendar = .current) -> Date {
calendar.startOfDay(for: dayAfter(using: calendar))
}
}
let calendar = Calendar.current
let date = Date()
let startOfDay = date.startOfDay(using: calendar)
let startOfNextDay = startOfDay.startOfNextDay(using: calendar)
let minutes = calendar.dateComponents([.minute], from: startOfDay, to: startOfNextDay).minute!
let year = date.year(using: calendar)
let month = date.month(using: calendar)
let day = date.day(using: calendar)
let dates = (0..<minutes).compactMap {
DateComponents(calendar: calendar, year: year, month: month, day: day, minute: $0).date
}
print("minutes count:", dates.count) // "minutes count: 1440n"
for minute in dates {
print("minute = (minute)")
}