ioscocoa-touchnsdatensdatepicker

Comparing dates in loop, then adding interval?


I've been really stuck on this one for a while. The user will set a custom alarm interval and then pick a date on the picker, and the app is set to display the next alarm. If they set it in the past, I want the app to add the interval by looping until it is in the future.

I've been playing around with the date comparisons but I can't seem to get anything to work. How would you guys accomplish this? Thanks!


Solution

  • You can add this extension to check if their date is before a given date:

    extension NSDate
    {
        func isGreaterThanDate(dateToCompare : NSDate) -> Bool
        {
            //Declare Variables
            var isGreater = false
    
            //Compare Values
            if self.compare(dateToCompare) == NSComparisonResult.OrderedDescending
            {
               isGreater = true
            }
    
           //Return Result
            return isGreater
        }
    
    
        func isLessThanDate(dateToCompare : NSDate) -> Bool
        {
            //Declare Variables
            var isLess = false
    
           //Compare Values
           if self.compare(dateToCompare) == NSComparisonResult.OrderedAscending
            {
                isLess = true
            }
    
            //Return Result
            return isLess
        }
    }
    

    And to use it, just do something like

    let today = NSDate()//this creates a date object with current date
    let isBeforeToday = today.isGreaterThanDate(aDate)//aDate is whatever date they pick from the picker
    

    And then to add your interval you can do

    today.dateByAddingTimeInterval(customInterval)//customInterval is in seconds
    

    I'm not sure I know exactly what you want to do, but this should at least get you started with comparing dates and adding intervals to them