当日期不在 2 个日期之内时,增加 2 个日期直到日期在之内。 Swift

While a date is not within 2 dates, increase the 2 dates until the date is within. Swift

我有以下代码,它具有由用户选择的选定日期的功能。这传递了从 CoreData 检索的 currentStart 和 endDate,我想根据传递到以下函数的先前 startDate 和 endDate 创建一个 newStartDate 和 newEndDate:

func calcStartAndEndDateBasedOnCurrentExsisting(selectedSpendDate: NSDate, currentStartDate: NSDate,
    currentEndDate: NSDate, durationOccurance: Double) {
    //initialising the newStartDate and newEndDate
    var newStartDate : NSDate = currentStartDate
    var newEndDate : NSDate = currentEndDate

    var occurance : Int
    //if the selectedSpendDate is before the currentStartDate, make the occurance a negative so it goes back in time. durationOccurance is how many days to increase/decrease by
    if selectedSpendDate.earlierDate(currentStartDate).isEqualToDate(selectedSpendDate)  {
        occurance = -Int(durationOccurance)

    }
    else {
        occurrence = Int(durationOccurance)
    }


        print("old end date = \(currentEndDate)")
        components.day = occurance

        while newStartDate.compare(selectedSpendDate) == .OrderedDescending || newEndDate.compare(selectedSpendDate) == .OrderedAscending {
            print("\(selectedSpendDate) is not within \(newStartDate) & \(newEndDate)")

            let test = newStartDate
            print("old start date = \(test)")
            let newDate = calendar.dateByAddingComponents(components, toDate: test, options: [])!

            newStartDate = newDate
            print("new StartDate = \(newStartDate)")

            //working out end date from the computed start date
            let calculatedEndDay = rangeOfPeriod(.Day, date: newStartDate).1
            components.day = Int(durationOccurance) - 1

            newEndDate = calendar.dateByAddingComponents(components, toDate: calculatedEndDay, options: [])!
            print("Start: \(newStartDate) End: \(newEndDate)")
        }

}

它最初似乎有效。例如,当 currentStartDate 是 24/03/2016 时,这会成功更改为 25/03/2016 但这永远不会更改为 26/03/2016.

输出如下所示:

old end date = 2016-03-24 23:59:59 +0000
2016-03-26 10:20:22 +0000 is not within 2016-03-24 00:00:00 +0000 & 2016-03-24 23:59:59 +0000
old start date = 2016-03-24 00:00:00 +0000
new StartDate = 2016-03-25 00:00:00 +0000
Start: 2016-03-25 00:00:00 +0000 End: 2016-03-25 23:59:59 +0000
2016-03-26 10:20:22 +0000 is not within 2016-03-25 00:00:00 +0000 & 2016-03-25 23:59:59 +0000
old start date = 2016-03-25 00:00:00 +0000
new StartDate = 2016-03-25 00:00:00 +0000

任何帮助将不胜感激:)

components.day = occurance 在 while 循环中时,它按预期工作