我正在使用 Swift 3,我想打印两个日期之间的每一天。
例如:
08-10-2017 -> 开始日期
08-15-2017 -> 结束日期
应该打印:
08-10-2017
08-11-2017
08-12-2017
08-13-2017
08-14-2017
08-15-2017
我想在两个特定日期获得范围,有人可以帮我吗?我试图将这两个日期放在 for 循环中,但没有机会。
我正在使用 Swift 3,我想打印两个日期之间的每一天。
例如:
08-10-2017 -> 开始日期
08-15-2017 -> 结束日期
应该打印:
08-10-2017
08-11-2017
08-12-2017
08-13-2017
08-14-2017
08-15-2017
我想在两个特定日期获得范围,有人可以帮我吗?我试图将这两个日期放在 for 循环中,但没有机会。
您需要创建一个基于日历的日期,并开始增加开始日期,直到达到结束日期。这是一个代码片段,如何做到这一点:
func showRange(between startDate: Date, and endDate: Date) {
// Make sure startDate is smaller, than endDate
guard startDate < endDate else { return }
// Get the current calendar, i think in your case it should some fscalendar instance
let calendar = Calendar.current
// Calculate the endDate for your current calendar
let calendarEndDate = calendar.startOfDay(for: endDate)
// Lets create a variable, what we can increase day by day
var currentDate = calendar.startOfDay(for: startDate)
// Run a loop until we reach the end date
while(currentDate <= calendarEndDate) {
// Print the current date
print(currentDate)
// Add one day at the time
currentDate = Calendar.current.date(byAdding: .day, value: 1, to: currentDate)!
}
}
用法:
let today = Date()
let tenDaysLater = Calendar.current.date(byAdding: .day, value: 10, to: today)!
showRange(between: today, and: tenDaysLater)