Search code examples
swiftnsdatenscalendar

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


I have the following code which has a function with a selected date which is chosen by a user. This passes in a currentStart and endDate which is retrieved from CoreData and i want to create a newStartDate and newEndDate based on the previous startDate and endDate which was passed into the below function:

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)")
        }

}

It seems to work for initially. For example when the currentStartDate is 24/03/2016, this changes successfully to the 25/03/2016 however this never changes to the 26/03/2016.

the output is shown below:

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

Any help would be appreciated :)


Solution

  • It works as expected when components.day = occurance is within the while loop