无法获取格式化NSDate

时间:2014-05-10 20:00:49

标签: ios objective-c nsdate nsdateformatter

我在格式化日期时遇到问题,因此我可以将其与EventKit一起使用以将其添加到日历中。日期来自bandsintown API的JSON,格式如下:

2014-05-10T19:00:00

我要添加到日历的代码就是这个。问题是newDate为null。

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
    NSString *formattedDateString = [dateFormatter stringFromDate:date];
    NSDate *newDate = [dateFormatter dateFromString:formattedDateString];

    NSLog(@"%@", newDate);

    EKEventStore *store = [[EKEventStore alloc] init];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (!granted)
        {
            return;
        }
        EKEvent *event = [EKEvent eventWithEventStore:store];
        event.title = titleString;
        event.location = venueString;
        event.startDate = newDate;
        event.endDate = [event.startDate dateByAddingTimeInterval:60*60];  //set 1 hour meeting
        [event setCalendar:[store defaultCalendarForNewEvents]];
        NSError *err = nil;
        [store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
    }];

1 个答案:

答案 0 :(得分:2)

您从JSON获取日期为字符串。因此没有意义 首先调用stringFromDate:(并且应该有一个"不兼容的指针警告")。 只需要dateFromString:

NSString *date = @"2014-05-10T19:00:00";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss"];
NSDate *newDate = [dateFormatter dateFromString:date];