Reputation: 365
I am trying to split a NSDate I receive from web service into two different dates in order to populate a tableView for events with sections for each day. I figured the least complicated way to do the latter is to create a fetch request looking for unique days.
So I try to create a NSDate "day" but having the time component set to 00:00. I wonder if there is a more efficient way to achieve this:
if (eventoItemList.count > 0) {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
NSDateFormatter *dayFormatter = [[NSDateFormatter alloc] init];
[dayFormatter setDateFormat:@"yyyy-MM-dd"];
for (GDataXMLElement *eventoItem in eventoItemList) {
BOEvent *event = [[BOEvent alloc] init];
NSString *idEventStr = [[[eventoItem elementsForName:@"id"] objectAtIndex:0] stringValue];
NSString *name = [[[eventoItem elementsForName:@"titulo"] objectAtIndex:0] stringValue];
NSString *type = [[[eventoItem elementsForName:@"tipo"] objectAtIndex:0] stringValue];
NSString *descr = [[[eventoItem elementsForName:@"descripcion"] objectAtIndex:0] stringValue];
NSString *address = [[[eventoItem elementsForName:@"direccion"] objectAtIndex:0] stringValue];
NSDate *date = [dateFormatter dateFromString:[[[eventoItem elementsForName:@"fecha"] objectAtIndex:0] stringValue]];
NSString *action = [[[eventoItem elementsForName:@"accion"] objectAtIndex:0] stringValue];
[event setIdEvent:[idEventStr integerValue]];
[event setName:name];
[event setType:type];
[event setDesc:descr];
[event setAddress:address];
[event setAction:action];
[event setDate:date];
[event setDayDate:[dayFormatter dateFromString:[dayFormatter stringFromDate:date]]];
[events addObject:event];
}
}
Thank you for your help.
Upvotes: 4
Views: 1244
Reputation: 50089
sample code for splitting a NSDate into two NSDates (date only, time only)
NSDate *date = [NSDate date];
NSCalendar *gregorian = [NSCalendar currentCalendar];
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
NSDateComponents *comps = [gregorian components:unitFlags fromDate:date];
NSDate *dateOnly = [gregorian dateFromComponents:comps];
unitFlags = NSHourCalendarUnit | NSMinuteCalendarUnit | NSDayCalendarUnit;
comps = [gregorian components:unitFlags fromDate:date];
NSDate *timeOnly = [gregorian dateFromComponents:comps];
NSLog(@"%@ = \n\tDate: %@ \n\tTime: %@", date, dateOnly, timeOnly);
sample code for outputting NSDate in two NSStrings
NSDate *date = [NSDate date];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateStyle:NSDateFormatterFullStyle];
[f setTimeStyle:NSDateFormatterNoStyle];
NSString *dateOnly = [f stringFromDate:date];
[f setTimeStyle:NSDateFormatterFullStyle];
[f setDateStyle:NSDateFormatterNoStyle];
NSString *timeOnly = [f stringFromDate:date];
NSLog(@"%@ = \n\tDate: %@ \n\tTime: %@", date, dateOnly, timeOnly);
Upvotes: 3