taylormade201
taylormade201

Reputation: 696

NSDateFormatter in loop

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"];

Upvotes: 0

Views: 199

Answers (2)

Hot Licks
Hot Licks

Reputation: 47739

It fails on subsequent iterations because you MODIFIED THE FORMAT near the bottom of the loop. What you probably want is two separate formatters, one for one format and one for the other, so you don't have to switch formats back and forth.

Upvotes: 0

bshirley
bshirley

Reputation: 8357

Side note, I think you should remove the index from the iteration entirely:

Also, you're resetting the formatter inside the loop…

for (NSString *dateString in [dict objectForKey:@"time"]) {
    dateString = [dateString stringByReplacingOccurrencesOfString:@"Z" withString:@" "];
    NSDate *date = [timeFormatter dateFromString:dateString];
    [tempDates addObject:date];
    [timeFormatter setDateFormat:@"EEE h:mm a"]; // RESETING DATE FORMAT - SECOND ITERATION WILL FAIL
    [tempDateStrings addObject:[timeFormatter stringFromDate:date]];

}

I suspect you want two formatters, ONE to read the string input, and a SECOND to output the value into the format you like.

Upvotes: 2

Related Questions