Search code examples
swiftnsdatexcode6

NSDate Comparison using Swift


I am working on an app the requires checking the due date for homework. I want to know if a due date is within the next week, and if it is then perform an action.
Most of the documentation I could find is in Objective-C and I can't figure out how to do it in Swift. Thanks for the help!!


Solution

  • I like using extensions to make code more readable. Here are a few NSDate extensions that can help clean your code up and make it easy to understand. I put this in a sharedCode.swift file:

    extension NSDate {
    
        func isGreaterThanDate(dateToCompare: NSDate) -> Bool {
            //Declare Variables
            var isGreater = false
    
            //Compare Values
            if self.compare(dateToCompare as Date) == ComparisonResult.orderedDescending {
                isGreater = true
            }
    
            //Return Result
            return isGreater
        }
    
        func isLessThanDate(dateToCompare: NSDate) -> Bool {
            //Declare Variables
            var isLess = false
    
            //Compare Values
            if self.compare(dateToCompare as Date) == ComparisonResult.orderedAscending {
                isLess = true
            }
    
            //Return Result
            return isLess
        }
    
        func equalToDate(dateToCompare: NSDate) -> Bool {
            //Declare Variables
            var isEqualTo = false
    
            //Compare Values
            if self.compare(dateToCompare as Date) == ComparisonResult.orderedSame {
                isEqualTo = true
            }
    
            //Return Result
            return isEqualTo
        }
    
        func addDays(daysToAdd: Int) -> NSDate {
            let secondsInDays: TimeInterval = Double(daysToAdd) * 60 * 60 * 24
            let dateWithDaysAdded: NSDate = self.addingTimeInterval(secondsInDays)
    
            //Return Result
            return dateWithDaysAdded
        }
    
        func addHours(hoursToAdd: Int) -> NSDate {
            let secondsInHours: TimeInterval = Double(hoursToAdd) * 60 * 60
            let dateWithHoursAdded: NSDate = self.addingTimeInterval(secondsInHours)
    
            //Return Result
            return dateWithHoursAdded
        }
    }
    

    Now if you can do something like this:

    //Get Current Date/Time
    var currentDateTime = NSDate()
    
    //Get Reminder Date (which is Due date minus 7 days lets say)
    var reminderDate = dueDate.addDays(-7)
    
    //Check if reminderDate is Greater than Right now
    if(reminderDate.isGreaterThanDate(currentDateTime)) {
        //Do Something...
    }