2016-03-25 18 views
0

Bir kullanıcı tarafından seçilen bir tarihle bir işlevi olan aşağıdaki kodu kullanıyorum. Bu currentStart içinde geçer ve CoreData alınır endDate ve ben aşağıda işlevi geçirildi önceki StartDate bitiştarihi dayalı bir newStartDate ve newEndDate oluşturmak istiyorum:Bir tarih 2 tarih içinde olmasa da, tarih, tarih olana kadar 2 tarihi artırın. Swift

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

} 

Başlangıçta için çalışmak gibi görünüyor. Örneğin, currentStartDate 24/03/2016 olduğunda, bu 25/03/2016 için başarılı bir şekilde değişir, ancak bu hiçbir zaman 26/03/2016 olarak değişmez.

çıkış aşağıda gösterilmiştir:

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 

Herhangi bir yardım mutluluk duyacağız :)

O components.day = occurance iken döngü içinde olduğunda beklendiği gibi çalışır

cevap

0