views:

39

answers:

1

I have a string in the format "Fri Jul 09 17:57:44 +0000 2010" which I need to convert to an NSDate.

I have tried a few unsuccessful operations to convert this date, and was wondering if anyone could tell me how I can achieve this.

Regards

A: 

Have you tried the brute force method:

This is untested, but should give you some idea of what to do.

// Set up some helper information
NSArray *monthArray = [NSArray arrayWithObjects:@"Jan", @"Feb", @"Mar",
                                                @"Apr", @"May", @"Jun",
                                                @"Jul", @"Aug", @"Sep",
                                                @"Oct", @"Nov", @"Dec", nil];
NSArray *ordinalArray = [NSArray arrayWithObjects:@"01", @"02", @"03",
                                                  @"04", @"05", @"06",
                                                  @"07", @"08", @"09",
                                                  @"10", @"11", @"12", nil];

NSDictionary *monthOrdinalDictionary = [NSDictionary dictionaryWithObjects:ordinalArray 
                                                         forKeys:monthArray];

// This is the date string to convert.
dateString = @"Fri Jul 09 17:57:44 +0000 2010"; 

// Split it into it's components
NSArray *dateComponentArray = [dateString componentsSeparatedByString:@" "];

// Create a new date string from the components in a format that NSDate understands
newDateString = [NSString stringWithFormat:@"%@-%@-%@ %@ %@", [dateComponentArray objectAtIndex:6],
                                   [monthOrdinalDictionary objectForKey:[dateComponentArray objectAtIndex:2]],
                                   [dateComponentArray objectAtIndex:3],
                                   [dateComponentArray objectAtIndex:4],
                                   [dateComponentArray objectAtIndex:5]];

// Create the date from this string
NSDate *dateTime = [NSDate dateWithString:newDateString];

Yes, it's ugly but you can refactor most of this out into a helper function. I haven't tested it, but you should have an idea of what to do: Take the date string, convert it into a string that NSDate can use to create a date, use this string to create the NSDate.

At least you'll have code to work on and you can go back and change it if it is a performance bottleneck.

Abizern
Why is this necessary?
Peter Hosey
Just an example of working through a block. using `dateWithNaturalLanguageString:locale` might work (I haven't tried it). I wanted to show a way just working through block when trying to develop an application just to get it working before going back and optimising code.
Abizern