My String Date是08-17-2016 10:30。我通过此代码将其转换为日期
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM-dd-yyyy HH:mm"];
NSDate *dateFromString= [dateFormatter dateFromString:eventDate];
NSLog(@"Date :%@",dateFromString);
我的nslog为 2016-08-17 05:00:00 +0000 。但我的时间是10:30。 我不想给结束日期,因为我希望它在那里直到用户删除它。
- (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];
}
答案 0 :(得分:1)
实际上您的日期是GMT格式,时间是-5.30小时,所以我们需要添加本地时区并检查
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);
输出
更新回答
试试这个
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
}];