I am having some issues with the following function. I have a dictionary with an array of date strings. I would like to loop through them and generate an NSDate object for each string. An example of the date string would be 20Z01NOV2011, where 20Z indicates 8:00 Zulu time, followed by the day,month, year.To make the date extraction easier, I remove the Z and insert a space.
The date formatter seems to work fine the first loop iteration, however fails on the subsequent iterations, however the input string format seems to be fine. Im not sure if there is a memory issue, and the string or formatter needs to be cleared, but I could use a hand correcting it.
NSDateFormatter *timeFormatter = [[NSDateFormatter alloc] init];
[timeFormatter setDateFormat:@"HH ddMMMyyyy"];
NSMutableArray *tempDates = [[NSMutableArray alloc] initWithCapacity:[[dict objectForKey:@"time"] count]];
NSMutableArray *tempDateStrings = [[NSMutableArray alloc] initWithCapacity:[[dict objectForKey:@"time"] count]];
for (int i=0; i < [[dict objectForKey:@"time"] count]; ++i) {
NSString *dateString = [[[dict objectForKey:@"time"] objectAtIndex:i] stringByReplacingOccurrencesOfString:@"Z" withString:@" "];
NSDate *date = [timeFormatter dateFromString:dateString];
[tempDates addObject:date];
[timeFormatter setDateFormat:@"EEE h:mm a"];
[tempDateStrings addObject:[timeFormatter stringFromDate:date]];
}
[dict setObject:tempDateStrings forKey:@"dateStrings"];
[dict setObject:tempDates forKey:@"dateObjects"];
Side note, I think you should remove the index from the iteration entirely:
Also, you’re resetting the formatter inside the loop…
I suspect you want two formatters, ONE to read the string input, and a SECOND to output the value into the format you like.