我是Xcode的初学者,并搜索以下代码,在我的应用内添加一个事件。但该示例仅显示如何使用[[NSDate alloc] init];
我可以获得哪些代码来设置我想要的日期,例如20-12-2012?
感谢您的时间。
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];
答案 0 :(得分:2)
正如您所发现的,将NSDate对象设置为非平凡日期完全不重要。
有几种方法可以做到这一点。
1)
查看the documentation for [NSDateFormatter dateFromString:]
。
<强> 2)强>
这是设定2012年12月20日的另一种方式。
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;