Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 675
bnjmn.myers Avatar asked Mar 06 '15 15:03

bnjmn.myers


1 Answers

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!)!
like image 163
lchamp Avatar answered Sep 23 '22 15:09

lchamp