Stuck with creating an event and formatting dates (Swift - EventKit - OS X)

752 views Asked by At

I have been stuck on trying to hardcode a new event. My difficulty lies especially with the dates and formatting

let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "MM'/dd'/YYYY"
    var dateString = "07/16/2015"
    var startDate = dateFormatter.dateFromString(dateString)
    var endDate = dateFormatter.dateFromString(dateString)


    var newEvent : EKEvent = EKEvent(eventStore: store)
    var error : NSError? = nil
    newEvent.title = "physiotherapy"
    newEvent.location = "London"
    newEvent.startDate = startDate
    newEvent.endDate = endDate
    newEvent.notes = "testing the event"

    self.store.saveEvent(newEvent, span: EKSpanThisEvent, commit: true, error: nil)

1) Some assistance as to how I achieve this correctly would be greatly appreciated

2) Also, how can I reference the calendar to use?

Thanks,

2

There are 2 answers

2
Aaron Brager On BEST ANSWER

dateString doesn't match the format you specified. Why not use the built-in short style?

This appears to work:

let dateFormatter = NSDateFormatter()
dateFormatter.dateStyle = .ShortStyle
var dateString = "07/16/2015"
var startDate = dateFormatter.dateFromString(dateString)
var endDate = dateFormatter.dateFromString(dateString)

startDate and endDate are optionals, so you'll have to unwrap them. In this example, I'm using the force-unwrap operator:

newEvent.startDate = startDate!
newEvent.endDate = endDate!

However, if the input data isn't guaranteed to produce a valid NSDate, you should unwrap the optionals normally and handle the error case.

1
zaph On

For year use use "yyyy", not "YYYY" for the year.

"Y" means year of "Week of Year"

See: ICU Formatting Dates and Times