atxnewb
atxnewb

Reputation: 23

IOS Swift Date Comparison

I have been hunting around but am having a hard time locating current relevant information that deals with a simple date year comparison. Most of the answers around googlesphere are a bit more console side rather than application side...

I have gotten a bit of the code wrote with the help of some tutorials ( this is my first ios app)

My issue is the integarValue does not work with NSDate and causes me an error. Having a hard time getting NSDateTimeInterval to work in my favor also...All help is greatly appreciated!!

    //grab the date needed
    var chosenDate = self.datePick.date

    //create todays date variable for math
    var todaysDate:NSDate = NSDate()

    // create a formatter
    var formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy"

    //time interval since now


    //grab the diff in years and display amount of years difference
    let day = formatter.stringFromDate(todaysDate.integarValue) - formatter.stringFromDate(chosenDate.integarValue)
    let result = "\(day)"

    //create alert controller
    let myAlert = UIAlertController(title: result, message: nil, preferredStyle: UIAlertControllerStyle.Alert)


    //add button to alert
    myAlert.addAction(UIAlertAction(title: "Close", style: UIAlertActionStyle.Default, handler: nil))
    //show alert
    self.presentViewController(myAlert, animated: true, completion: nil)
}

Upvotes: 0

Views: 139

Answers (2)

jperl
jperl

Reputation: 1116

  1. Spelling

    integer, not integar,

  2. Use NSDate in -stringFromDate

    -stringFromDate accepts an NSDate as its argument, so your code should look like this: formatter.stringFromDate(todaysDate)

  3. Convert string back to integer before subtracting

    stringFromDate returns a String, and there is no default definition for binary subtraction between String objects, so you must use toInt() and then unwrap the value with ! before you subtract

    todaysDateString = formatter.stringFromDate(todaysDate)
    println(todaysDateString-1) // This will give you an error
    todaysDateInteger = todaysDateString.toInt()!
    println(todaysDateInteger-1) // This works
    

Putting it all together

//grab the diff in years and display amount of years difference
let day = formatter.stringFromDate(todaysDate).toInt()! - formatter.stringFromDate(chosenDate).toInt()!

This is what that line of code should look like.

Upvotes: 1

Leo Dabus
Leo Dabus

Reputation: 236568

let yearsDifference = NSCalendar.currentCalendar().components(.CalendarUnitYear, fromDate: datePick.date, toDate: NSDate(), options: nil).year

Upvotes: 2

Related Questions