在iPhone中将事件添加到默认日历

时间:2012-08-20 06:12:05

标签: iphone ios

我正在尝试将该事件添加到iPhone默认日历中,代码如下

NSMutableString * startDateString = [NSMutableString stringWithString:@“11/20/2012 10:00 AM”];

NSMutableString * endtDateString = [NSMutableString stringWithString:@“11/20/2012 5:00 PM”];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// this is imporant - we set our input date format to match our input string
// if format doesn't match you'll get nil from your string, so be careful
[dateFormatter setDateFormat:@"MM-dd-yyyy HH:mm a"];


NSDate * startDate = [[NSDate alloc]init];
startDate = [dateFormatter dateFromString:startDateString];

NSDate *endDate = [[NSDate alloc]init];
endDate = [dateFormatter dateFromString:endtDateString];


EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
event.title     = @"TEST";
event.startDate = startDate;
event.endDate   = endDate;
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];


[startDate release];
[endDate release];


if(!err)
{

    UIAlertView *alertview=[[UIAlertView alloc]initWithTitle:@"TEST" message:@"Event Added successfully " delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];

    [alertview show];
    [alertview release];

}


NSLog(@"error is %@",err);

}

该事件已成功添加,但问题是它没有添加到事件开始日期,只是添加到2001年1月1日所有事件仅添加到同一日期。

任何人都可以在我出错的地方帮助我。我正在使用iPhone 4s& iPhone 3gs与5.1.1版本。

提前致谢。

1 个答案:

答案 0 :(得分:1)

将DateFormat设置为dateFormatter,如下所示:

[dateFormatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];

注意:yourdateString应该根据dateFormatter