1

我正在尝试将事件添加到 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 日日期,所有事件都仅添加到同一日期。

任何人都可以帮我解决我出错的地方吗?我使用的是 5.1.1 版本的 iPhone 4s 和 iPhone 3gs。

提前致谢 。

4

1 回答 1

1

像这样将 DateFormat 设置为 dateFormatter:

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

注意:yourdateString 应根据 dateFormatter

于 2012-08-20T06:31:32.640 回答