Clarence
Clarence

Reputation: 1943

Set a specific date of event to iCal in EKEvent

I am a beginner in Xcode and searched the following codes for adding an event into ical inside my app. But the example only show me how to set the start day and end day using [[NSDate alloc] init];

What code i can get in order to set the date as I want e.g. 20-12-2012?

Thanks for your time.

EKEventStore *eventDB = [[EKEventStore alloc] init];

EKEvent *myEvent  = [EKEvent eventWithEventStore:eventDB];

myEvent.title     = @"New Event";
myEvent.startDate = [[NSDate alloc]init ];

myEvent.endDate   = [[NSDate alloc]init ];
myEvent.allDay = YES;

[myEvent setCalendar:[eventDB defaultCalendarForNewEvents]];

NSError *err;

[eventDB saveEvent:myEvent span:EKSpanThisEvent error:&err]; 


    UIAlertView *alert = [[UIAlertView alloc]
                          initWithTitle:@"Event Created"
                          message:@"Yay!?"
                          delegate:nil
                          cancelButtonTitle:@"Okay"
                          otherButtonTitles:nil];
    [alert show];

Upvotes: 0

Views: 2092

Answers (1)

Michael Dautermann
Michael Dautermann

Reputation: 89559

As you've discovered, setting a NSDate object to non-trivial dates is entirely non-trivial.

There's a couple ways to do this.

1)

Check out the documentation for [NSDateFormatter dateFromString:].

2)

Here's another way to set December 20th, 2012.

NSCalendar * gregorian = [NSCalendar currentCalendar];
NSDate *currentDate = [NSDate dateWithTimeIntervalSinceReferenceDate: 0];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear: 11]; // 11 years past the reference date of 1-January-2001
[comps setMonth: 11]; // 11 months past January
[comps setDay:19]; // 19 days past the first day of January
NSDate *eventDate = [gregorian dateByAddingComponents:comps toDate:currentDate  options:0];

NSLog( @"event date is %@", [eventDate description] );
[comps release]; // NSDateComponents was explicitly alloc'd & init'd

myEvent.startDate = eventDate;
mtEvent.endDate = eventDate;

Upvotes: 2

Related Questions