Question

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

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top