puks1978 puks1978 - 2 months ago 11x
Swift Question

NSDate from String for eventkit

I have a swift app that allows users to store events in the default calendar. Everything seems to be working fine except 1 part. I allow users to set a start and end date from a date picker. The format is is

Sunday 21 Aug, 11:05 pm

I had a save button which takes this date and I am trying to convert it to a valid NSDate using

let startDate = "\(txtStartDate.text!)"
let endDate = "\(txtEndDate.text!)"
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEEE d MMM, h:mm a"

event.title = "\(txtEventTitle.text!)"
event.startDate = dateFormatter.dateFromString(startDate)!
event.endDate = dateFormatter.dateFromString(endDate)!
event.notes = "\(txtNotes.text!)"
event.calendar = eventStore.defaultCalendarForNewEvents

But for some reason it wont save the event. If I change the start date to

event.startDate = NSDate()

everything works great so I know it is saving.

Not sure what I am missing with the conversion.



Actually that's what Playgrounds are for ...

Copy and paste the code into a Playground and you will see that the date formatter returns nil for the given string and date format.

The issue is the locale. You have to set the locale explicitly to en_US_POSIX to ensure that the code works independent of the current locale.

Source : Technical Q&A QA1480 NSDateFormatter and Internet Dates

let startDate = "Sunday 21 Aug, 11:05 pm"
let dateFormatter = NSDateFormatter()
dateFormatter.locale = NSLocale(localeIdentifier: "en_US_POSIX")
dateFormatter.dateFormat = "EEE dd MMM, h:mm a"

let eventStartDate = dateFormatter.dateFromString(startDate)!