从上午9点到下午11点获取一天中的所有时间(以日期格式),并保存在Swift中的数组中,可以使用以下代码实现:
import Foundation
let calendar = Calendar.current
var allTimes = [Date]()
let startDate = calendar.date(bySettingHour: 9, minute: 0, second: 0, of: Date())!
let endDate = calendar.date(bySettingHour: 23, minute: 0, second: 0, of: Date())!
var currentDate = startDate
while currentDate <= endDate {
allTimes.append(currentDate)
currentDate = calendar.date(byAdding: .hour, value: 1, to: currentDate)!
}
// 打印所有时间
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
for time in allTimes {
let formattedTime = dateFormatter.string(from: time)
print(formattedTime)
}
上述代码中,首先使用Calendar.current
获取当前的日历对象。然后,通过calendar.date(bySettingHour:minute:second:of:)
方法设置起始时间为上午9点和结束时间为下午11点。接下来,使用一个循环从起始时间开始,每次增加1小时,直到达到结束时间为止。在每次循环中,将当前时间添加到allTimes
数组中。最后,使用DateFormatter
将日期格式化为字符串,并打印出来。
请注意,这只是一个示例代码,用于演示如何获取一天中的所有时间,并保存在Swift数组中。在实际应用中,您可能需要根据具体需求进行适当的调整和优化。
领取专属 10元无门槛券
手把手带您无忧上云