0

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,

Yelims01
  • 47
  • 1
  • 8
  • What do you need to do with the calendar? It defaults to the calendar formed from the settings for the current user’s chosen system locale overlaid with any custom settings the user has specified in System Preferences. – zaph Jun 16 '15 at 00:23
  • Consider accepting answers that are helpful, it rewards the people who take the time to answer and increases your reputation. Voting up a question or answer signals to the rest of the community that a post is interesting, well-researched, and useful, while voting down a post signals the opposite: that the post contains wrong information, is poorly researched, or fails to communicate information. Click on the hollow checkmark next to the answer that is best. [See this page for more detail](http://meta.stackoverflow.com/questions/5234/how-does-accepting-an-answer-work). – zaph Jun 16 '15 at 00:59
  • dateFormatter.dateFormat = "MM/dd/yyyy" – Leo Dabus Jun 16 '15 at 01:05

2 Answers2

0

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

"Y" means year of "Week of Year"

See: ICU Formatting Dates and Times

zaph
  • 111,848
  • 21
  • 189
  • 228
  • would you be able to give an example of full code that creates an event for OS X? One that will show in the Calendar? – Yelims01 Jun 20 '15 at 22:45
0

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.

Aaron Brager
  • 65,323
  • 19
  • 161
  • 287