迭代一年以上以获得 Swift 中的每一天 NSDate 对象

Iterating over a year to get each days NSDate object in Swift

你好,我有一个方法,每天 returns 一组时间。

prayTimesDate(date: NSDate, latitide : Double, longitude : Double, timeZone : Double) -> NSMutableArray

我需要遍历一整年或者可能是一个日期范围,以获得一整年中每一天的时间数组。我在 ruby 和 python 中找到了很多关于如何执行此操作的参考资料,但我找不到 swift 或 objective-c 的任何内容。 swift 中是否有任何内置方法可以完成此操作?如果没有,有人可以帮助我,因为我还是编程新手。非常感谢任何输入。

这是我链接到我的 swift 项目的方法的 objective-c 代码

- (NSMutableArray *)prayerTimesDate:(NSDate *)date latitude:(double)latitude longitude:(double)longitude andTimezone:(double)timezone
{
    unsigned unitFlags = NSCalendarUnitYear | NSCalendarUnitMonth |  NSCalendarUnitDay;
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:unitFlags fromDate:date];

    NSInteger year = [components year];
    NSInteger month = [components month];
    NSInteger day = [components day];

    return [self getDatePrayerTimesForYear:year month:month day:day latitude:latitude longitude:longitude andtimeZone:timezone];
}

为 1 天创建一个 NSDateComponents 个实例,并在第一天的每个时间创建一个 NSDate 个对象。现在你可以遍历你想要的天数(或者直到你到达结束日期)然后你可以使用日历的 dateByAddingComponents:toDate:options: 来获取每一天的新日期。

假设您的 prayerTimesDate: 方法已经返回预期结果,您可以循环遍历一年中的每一天,同时重复调用 prayerTimesDate: 以获得包含每一天祈祷时间的数组,例如:

func yearlyPrayerDatesFromCurrentDate (latitude:Double, longitude:Double, timezone:Double) -> NSMutableArray {

    // Set "date" to equal the current day
    var date:NSDate! = NSDate()

    // Increment "date" by one year to calculate the ending
    // date for the loop
    let gregorian:NSCalendar! = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
    let dateComponents = NSDateComponents()
    dateComponents.year = 1
    let endingDate:NSDate! = gregorian.dateByAddingComponents(dateComponents, toDate: date, options: nil)

    // Create an array to hold *all* the returned 
    // results for the year
    var datesArray = NSMutableArray()

    // Loop through each date until the ending date is
    // reached
    while date.compare(endingDate) != NSComparisonResult.OrderedDescending {
        // Call your prayerTimesDate: method on the current
        // date to get that date's prayer times and add the
        // times from the returned array to the datesArray
        datesArray.addObjectsFromArray(prayerTimesDate(date, latitude: latitude, longitude: longitude, andTimezone: timezone))

        // increment the date by 1 day
        let dateComponents = NSDateComponents()
        dateComponents.day = 1
        date = gregorian.dateByAddingComponents(dateComponents, toDate: date, options: nil)
    }

    return datesArray
}

这是另一个超过 14 天的例子(没有 NSCalendar):

let ti:NSTimeInterval = 24*60*60 //one day
let dateFrom = NSDate() //Now
let dateTo = dateFrom.dateByAddingTimeInterval(24*60*60*14) //14 Days later

var nextDate = NSDate()
var endDate = dateTo.dateByAddingTimeInterval(ti)

while nextDate.compare(endDate) == NSComparisonResult.OrderedAscending
{      
    print("nextDate:", nextDate)
    nextDate = nextDate.dateByAddingTimeInterval(ti)
}

来自 Apple 文档:要计算一系列日期,请使用 enumerateDatesStartingAfterDate:matchingComponents:options:usingBlock: 方法,而不是在具有前一个循环迭代结果的循环中调用此方法 (- nextDateAfterDate:matchingComponents:options:)。

如我所知,它将迭代所有与 "matchingComponents" 匹配的日期,直到您完成 "stop.memory = true"

的迭代
//: Playground - noun: a place where people can play

import UIKit

let calendar = NSCalendar.currentCalendar()
let startDate = calendar.startOfDayForDate(NSDate())
let finishDate = calendar.dateByAddingUnit(.Day, value: 10, toDate: startDate, options: [])
let dayComponent = NSDateComponents()
dayComponent.hour = 1

calendar.enumerateDatesStartingAfterDate(startDate, matchingComponents: dayComponent, options: [.MatchStrictly]) { (date, exactMatch, stop) in
    print(date)
    if date!.compare(finishDate!) == NSComparisonResult.OrderedDescending {
        // .memory gets at the value of an UnsafeMutablePointer
        stop.memory = true
    }
}