我是iOS的新手,我面临着将数据从网络服务显示到日历的问题。
我的代码就像这样
-(void)funAddEvents:(NSArray *)arrDate
{
_eventsByDate = [NSMutableDictionary new];
for(int i=0;i<arrDate.count;i++)
{
NSString *datefromweb= [NSString stringWithFormat: @"%@",[[arrDate objectAtIndex:i] objectForKey:@"Date"]]; //Showing error on this like..
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MM/dd/yyyy hh:mm:ss a"];
NSDate *randomDate = [[NSDate alloc] init];
randomDate = [df dateFromString:datefromweb];
NSString *key = [[self dateFormatter] stringFromDate:randomDate];
// NSLog(@"event date =%@",randomDate);
if(!_eventsByDate[key])
{
_eventsByDate[key] = [NSMutableArray new];
}
[_eventsByDate[key] addObject:randomDate];
// NSLog(@"afte event date %@",eventsByDate);
}
}
提前致谢!
答案 0 :(得分:1)
arrDate
是String
的数组,而不是Dictionary
的数组,但由于错误的dateFormat
,您的数字也为零。正确的字符串日期格式为yyyy/MM/dd
,目前您将dateFormat
设置为MM/dd/yyyy hh:mm:ss a
这是错误的,因此更改dateFormat
将解决您的问题。
for(int i=0;i<arrDate.count;i++)
{
NSString *datefromweb= [NSString stringWithFormat: @"%@",[[arrDate objectAtIndex:i] objectForKey:@"Date"]]; //Showing error on this like..
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy/MM/dd"];
NSDate *randomDate = [[NSDate alloc] init];
randomDate = [df dateFromString:datefromweb];
NSString *key = [[self dateFormatter] stringFromDate:randomDate];
// NSLog(@"event date =%@",randomDate);
if(!_eventsByDate[key])
{
_eventsByDate[key] = [NSMutableArray new];
}
[_eventsByDate[key] addObject:randomDate];
// NSLog(@"afte event date %@",eventsByDate);
}