Imran Imran - 1 year ago 91
Objective-C Question

EKEventStore : Event is not adding in Device Calendar from Start Date only

My String Date is 08-17-2016 10:30. I am converting it to date by this code

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM-dd-yyyy HH:mm"];
NSDate *dateFromString= [dateFormatter dateFromString:eventDate];
NSLog(@"Date :%@",dateFromString);

I am getting nslog as 2016-08-17 05:00:00 +0000. but my time is 10:30.
I dont want to give end date because i want it to be there till user delete it.

- (void)addEventinCalendar:(NSString *)eventTitle andEventDate:(NSString *)eventDate

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM-dd-yyyy HH:mm"];

NSDate *dateFromString;
dateFromString = [dateFormatter dateFromString:eventDate];
NSLog(@"Date :%@",dateFromString);
//Date :2016-08-17 05:00:00 +0000

EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];

event.title = eventTitle;
event.startDate = dateFromString;
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];


Answer Source

actually your Date is GMT format, the time is -5.30 hrs so we need to add the local timeZone and check

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm"]; // set date format as per your String
NSDate *dateFromString= [dateFormatter dateFromString:@"2016-08-17 10:30"];
NSTimeInterval timeZoneSeconds = [[NSTimeZone localTimeZone] secondsFromGMT];
NSDate *dateInLocalTimezone = [dateFromString dateByAddingTimeInterval:timeZoneSeconds];
NSLog(@"Date :%@",dateInLocalTimezone);


enter image description here

updated answer

try this

 EKEventStore *store = [[EKEventStore alloc] init];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
  if (!granted) return;
  EKEvent *event = [EKEvent eventWithEventStore:store];
  event.title = @"Imran Verified";
  event.startDate = [NSDate date]; // today
  event.endDate = [event.startDate dateByAddingTimeInterval:60*60];  // Duration 1 hr
  [event setCalendar:[store defaultCalendarForNewEvents]];
  NSError *err = nil;
  [store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
  NSString *savedEventId = event.eventIdentifier;  // Store this so you can access this event later