0
votes

Ive got a UIDatepicker attached to a text field named dateField. when the user clicks on the field, a UIDatePicker pops up and the user chooses a date of birth. That date is saved as a string to that dateField and shows up formatted according to the users location ie May 4 1990 in USA or 4 May 1990 in Australia.

Later when they press a save button, I want to save the date to CoreData. I've been trying to convert the date string back to an NSDate but i keep running into problems and getting a nil date.

I believe in need to set the NSDateFormatter locale and timezone before doing this so i set it to the user's currentLocale and localTimeZone. I also believe I need to set a date format ... if i set the date format to "dd MMM yyyy" the NSDate works if the users locale is Australia but not if i set the locale to USA.

How can i set the date format so that it allows the dateFromString method to work regardless of the user's locale. Or should i be doing this differently (ie save a birthdate as a String rather than an NSDate unique point in time)

my code

    let dateStr = "20 Aug 1990" //suppose dateField contains this string as saved from a UIDatePicker (formatted according to the user's locale ... ie would be Aug 20 1990 in USA locale)
    let formatter = NSDateFormatter()
    formatter.locale = NSLocale.currentLocale()
    formatter.timeZone = NSTimeZone.localTimeZone()
    formatter.dateFormat = "dd MMM yyyy" //how can i set this to be non-locale specific

    var dobStr = dobField.text
    var dob: NSDate? = formatter.dateFromString(dobStr)
    println(dob) //prints nil if user locale is USA
2

2 Answers

2
votes
let date: Date = myDatePicker.date

I haven't tested it, but the docs suggest it should work.

1
votes

I think I've fixed it. I think the thing that was causing problem was that I was setting locale to currentLocale but then 2 lines down specifying a dateFormat which would work if it corresponds to the current locale but not otherwise. Anyway, fix appears to be just specify locale and let that setting dictate the format used.