agf119105
agf119105

Reputation: 1810

storing date in coredata swift

I have a textfield connected to a date picker

I am then trying to store the selected date into core data,

My log off the date picked by the user seems ok:

2016-01-29 00:00:00 +0000 [I strip the time component with some code]

This is converted into a String and displayed in the textfield called startDate.

func handleDatePicker(sender: UIDatePicker) {
        let dateFormatter = NSDateFormatter()
        dateFormatter.dateFormat = "EEE, dd MMM YYYY"
        startDate.text = dateFormatter.stringFromDate(sender.date)
    }

Now the strange thing is that when I try and store this into CoreData and convert the string back into a date (the attribute I am saving it into is configured as a Date)

let cont = self.context
        let newCustomer = NSEntityDescription.entityForName("Customer", inManagedObjectContext: cont)
        let aCust = Customer(entity: newCustomer!, insertIntoManagedObjectContext: cont)

let DF = NSDateFormatter()
        DF.dateFormat = "EEE, dd MMM YYYY"
        aCust.c15das = DF.dateFromString(startDate.text!)
        print("Saved Date: \(DF.dateFromString(startDate.text!))")

Now the log prints out:

2015-12-25 00:00:00 +0000

Why the difference? How can I stop this happening?

Sorry if its something obvious that I am not spotting.

Upvotes: 1

Views: 749

Answers (2)

vikingosegundo
vikingosegundo

Reputation: 52227

"EEE, dd MMM YYYY" -> YYYY: "Week of Year Calendar", aka "ISO Week Date System". The first week does not start on the first January. If the January 1st is either Monday, Tuesday, Wednesday or Thursday, the whole week is the first week of the new year. if it is Friday, Saturday or Sunday the week is the 53rd week of the last year. So this is a calendar with year that only have integral weeks. Either 52 or 53, rather than 365 or 366 days.
In this calendar January 29th would be the 5th day of the 4th week of the year 2016 — 2016-W4-5. This system does not know months and therefor your date is nonsense.

You want "EEE, dd MMM yyyy", as yyyy indicates a year that starts on 1st of January and ends after 31st of December — The Gregorian Year.


[I strip the time component with some code]

You shouldn't do that. Rather NSCalendar's method to get a date at the beginning of the day.

var today: NSDate?
cal.rangeOfUnit(.Day, startDate: &today, interval: nil, forDate: date)

Upvotes: 2

Tom el Safadi
Tom el Safadi

Reputation: 6746

Try this code, that worked for me:

let dateString = "Fri, 29 Jan 2016" // change to your date format

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE, dd MMM yyyy"
dateFormatter.timeZone = NSTimeZone(name: "UTC")

let date = dateFormatter.dateFromString(dateString)
print(date!)

Upvotes: 0

Related Questions