次のような関数シグネチャがあると考えてください。
func datesRange(from: Date, to: Date) -> [Date]
これは、from
日付とto
日付のインスタンスを受け取り、パラメーター間の日付(日)を含む配列を返す必要があります。それを達成する方法は?
次のように実装できます。
func datesRange(from: Date, to: Date) -> [Date] {
// in case of the "from" date is more than "to" date,
// it should returns an empty array:
if from > to { return [Date]() }
var tempDate = from
var array = [tempDate]
while tempDate < to {
tempDate = Calendar.current.date(byAdding: .day, value: 1, to: tempDate)!
array.append(tempDate)
}
return array
}
使用法:
let today = Date()
let nextFiveDays = Calendar.current.date(byAdding: .day, value: 5, to: today)!
let myRange = datesRange(from: today, to: nextFiveDays)
print(myRange)
/*
[2018-03-20 14:46:03 +0000,
2018-03-21 14:46:03 +0000,
2018-03-22 14:46:03 +0000,
2018-03-23 14:46:03 +0000,
2018-03-24 14:46:03 +0000,
2018-03-25 14:46:03 +0000]
*/
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加