2016-08-17 160 views
0

我的字符串日期爲08-17-2016 10:30。我這段代碼EKEventStore:僅在開始日期後纔在設備日曆中添加事件

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

我得到的NSLog將其轉換爲日期2016年8月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]; 

} 

回答

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); 

輸出

enter image description here

已更新的回答

試試這個

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 
}]; 
+0

即時得到的日期,但它不是在日曆 – ChenSmile

+0

@Imran加入 - 快樂兄弟,確定在這裏嘗試貼出或不是一次靜態數據,如果我們公佈與日期查詢,OK你可以更新的問題 –

+0

@Imran - 這意味着你的日期問題解決了正確 –

相關問題