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

时间:2015-01-24 20:54:35

标签: ios swift nsdate nsdatecomponents

您好我有一个方法,每天都会返回一个数组。

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

我需要遍历一整年或者一个日期范围,以获得一年中每一天的一系列时间。我在ruby和python中找到了很多关于如何做到这一点的参考资料,但是我找不到任何快速或客观的东西。 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];
}

4 个答案:

答案 0 :(得分:5)

假设您的prayerTimesDate:方法已经返回预期结果,您可以循环浏览一年中的每一天,同时反复调用prayerTimesDate:以获取包含每天祷告时间的数组,例如:< / p>

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
}

答案 1 :(得分:2)

以下是超过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)
}

答案 2 :(得分:0)

在第一天为每天创建一个NSDateComponents个实例和NSDate个对象。现在,您可以迭代所需的天数(或直到您达到结束日期为止),然后您可以使用日历的dateByAddingComponents:toDate:options:来获取每天的新日期。

答案 3 :(得分:0)

来自Apple doc:要计算日期序列,请使用enumerateDatesStartingAfterDate:matchingComponents:options:usingBlock:方法,而不是在前一循环迭代的循环中调用此方法( - nextDateAfterDate:matchingComponents:options:)&#39;结果。

正如我所说,它将迭代与&#34;匹配组件&#34;匹配的所有日期。直到你用&#34; stop.memory = true&#34;

完成迭代
//: 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
    }
}