返回两个日期之间的日期数组的方法 - Swift 3

时间:2017-02-25 23:24:41

标签: swift date calendar swift3

我试图在我的一个物体的时间戳和未来30天之间获得一系列日期。

我已经使用了下面的代码,但我没有得到理想的结果,并且无法尝试制作标题中描述的方法。任何帮助都会很棒,谢谢。

var dates = [Date]()
    func fetchDays() {
            let cal = Calendar.current

            var dateComponents = DateComponents()
            dateComponents.year = 2017
            dateComponents.month = 2
            dateComponents.day = 12

            guard let startDate = cal.date(from: dateComponents) else {
                return }

            var start = cal.startOfDay(for: startDate)

            for _ in 0 ... 30 {
    guard let daysBetween = cal.date(byAdding: .day, value: 1, to: startDate) else { return }
                start = daysBetween
                dates.append(start)
            }
        }

2 个答案:

答案 0 :(得分:2)

您在相同的开始日期添加1,因此您的数组会反复填充相同的日期。只需用循环索引+ 1替换1

for i in 0 ... 30 {
    if let newDate = cal.date(byAdding: .day, value: i + 1, to: startDate) {
        dates.append(newDate)
    }
}

您不需要start变量。

答案 1 :(得分:0)

嗨@Breezy让它工作你只需要改变一件小事

将start参数的值改为start:

  for _ in 0 ... 30 {
    guard let daysBetween = cal.date(byAdding: .day, value: 1, to: start) else { return }
                start = daysBetween
                dates.append(start)
            }

编辑:

如果您不想使用30天,则可以添加月末,然后获取两个日期之间的日期,如下所示:

var dates = [Date]()
        func fetchDays() {
            let cal = Calendar.current

            var dateComponents = DateComponents()
            dateComponents.year = 2017
            dateComponents.month = 2
            dateComponents.day = 12

            guard let startDate = cal.date(from: dateComponents) else {
                return }

            var start = cal.startOfDay(for: startDate)
            guard let endDate = cal.date(byAdding: .month, value: 1, to: start) else { return }

            guard let daysBetween = cal.dateComponents([.day], from: start, to: endDate).day else { return }

            for _ in 0 ... daysBetween {
                guard let newDate = cal.date(byAdding: .day, value: 1, to: start) else { return }
                start = newDate
                dates.append(newDate)
            }
        }