NSDateFormatter and date conversion not working
cocoa, cocoa-touch, ios-simulator, objective-c
Solution
Problem appears to be your region setting is not "en-US" so the date formatter doesn't parse the string using the en-US format supplied. Although there may be a more elegant, general solution, doing a setLocale on originalDateFormatter to en_US can be used as a workaround to solve the problem.
As you've already tried in your code:
[originalDateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
Problem
I am developing an app for the iPhone where I need to convert an date from an XML feed into just a HH:MM format. I have the following method that doesn't work and I have no clue what I am doing wrong. As an example, the timeToConvert string would be: "Mon, 01 Feb 2010 21:55:00 +0100" (without the quotes) The method works when the region is set to US (I get back the correct date), but not when I change the region (in Settings->General->International) to Spain, or other regions (in that case I get back nil). ``` - (id)timeConvertToHHMM:(NSString *)timeToConvert { NSString *newPubDate = timeToConvert; //Let's remove any rubbish from the code newPubDate = [newPubDate stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]; //create formatter and format to convert the XML string to an NSDate NSDateFormatter *originalDateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [originalDateFormatter setDateFormat:@"EEE, d MMM yyyy H:mm:ss z"]; //run the string through the formatter NSDate *formattedDate = [[NSDate alloc] init]; formattedDate = [originalDateFormatter dateFromString:newPubDate]; //Let's now create another formatter to take the NSDate and convert format it to Hours and minutes NSDateFormatter *newDateFormatter = [[[NSDateFormatter alloc] init] autorelease]; [newDateFormatter setDateFormat:@"HH:mm"]; // 24H clock set // And let's convert it back to a readable string NSString *calcHHMM = [newDateFormatter stringFromDate:formattedDate]; NSLog(@"CalcHHMM: %@", calcHHMM); return calcHHMM; } ``` Any hint on why this is not working, and just returning NULL will be more than welcome.