Search code examples
swiftnsdateformatter

Swift date formatting


I'm trying to pull a date string from a button and format is as a date to be store in CoreData.

Here is my code:

let dateStr = setDateBTN.titleLabel?.text
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "MM-dd-YYYY"
let date:NSDate = dateFormatter.dateFromString(dateStr!)!

If I do a println on dateStr I get the following: 03-10-2015. Then if I immediately println on date I get: 2014-12-21 05:00:00 +0000.

Any ideas as to why the actual date is changing when I run it through the date formatter?


Solution

  • NSDateFormatter Class Reference : http://goo.gl/7fp9gl

    Date Formatting Guide (Apple) : http://goo.gl/8zRTQl

    A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar.

    Your code should work, as you expect, like this :

    let dateStr = setDateBTN.titleLabel?.text
    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MM-dd-yyyy"
    let date:NSDate = dateFormatter.dateFromString(dateStr!)!