在Swift中如何获取两个日期之间的日期数组?

4

考虑我们有一个函数声明:

func datesRange(from: Date, to: Date) -> [Date]

需要编写一个函数,接受fromto日期实例,并返回包含其参数之间的日期(天数)的数组。如何实现?


1个回答

28

你可以像这样实现:

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]
*/

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接