5

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
bnjmn.myers
  • 409
  • 2
  • 6
  • 15
  • 2
    Lookup the documentation: The format for years is "yyyy" with lowercase y. (And you are not the first here to make this error :) – Martin R Mar 06 '15 at 15:32
  • Thanks, Martin. I originally had it as lowercase and something else wasn't working so I just in a grasp for help changed it to uppercase. – bnjmn.myers Mar 06 '15 at 15:52
  • I've just released a library which can help to work with NSDate in Swift; hope it helps: https://github.com/malcommac/SwiftDate – danielemm May 08 '15 at 12:13

1 Answers1

9

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!)!
lchamp
  • 6,592
  • 2
  • 19
  • 27
  • be aware that in modern iOS per Apple you must do this: https://stackoverflow.com/a/42370648/294884 (which is easier fortunately!) – Fattie Jul 28 '17 at 13:55