Question

I have a problem with NSDateFormatter and iOS. I actually found a recognition AND an explanation of the problem here:

http://www.cocoanetics.com/2011/12/ios-5-breaking-nsdateformatter/

However, my brain is not able to process that information to translate that all to a solution for my particular situation. I hope you guys 'n gals can help me out here:

Could anyone tell me how to make the following work in iOS5? It used to be working fine:

NSLocale *myLocale = [[NSLocale alloc] initWithLocaleIdentifier:@”en_GB”];
[inputFormatter setLocale: myLocale];
[myLocale release];
[inputFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
NSDate *formattedDate = [inputFormatter dateFromString: feedDateString];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"EEEE d MMMM"];

The input string, that is beyond my control, would be something like “Tue, 03 Jan 2012 00:00:00 +0100″ When I log [outputFormatter stringFromDate:formattedDate] I get null

The original Locale was “en_US”, but I changed that in the hope that that would help.

It would also help the people at this post, that seems to be a dead-end post:

NSDateFormatter on ios 5 - any other way to use?

Was it helpful?

Solution 2

To all of you having spent brain time on this: It all was my stupid own fault: The input string that needed to be formatted was not "Mon, 13 Feb 2012 00:00:00 +0100" but it was actually "Mon, 13 Feb 2012 00:00:00 +0100 " You see? Well, I didn't see the trailing white spaces during NSLogging. [Irony: the many spaces and return after the string are not displayed here either!]

And somehow, iOS 4 didn't care about it. iOS5 just is much more picky, and likely rightly so. So I solved the thing as follows:

NSString *trimmedString = [inputstring stringByTrimmingCharactersInSet:
                               [NSCharacterSet whitespaceAndNewlineCharacterSet]];

I hope that this can be of help to you as well.

OTHER TIPS

Try this:

NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
        
NSString *str = [outputFormatter stringFromDate:[NSDate date]];
/* 
   Do something with this string
*/
[outputFormatter release];

You might also add Region by adding setLocale parameter to NSDateFormatter.

NSLocale *myLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init];
[outputFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss Z"];
[outputFormatter setLocale: myLocale];
        
NSString *str = [outputFormatter stringFromDate:[NSDate date]];

/* 
   Do something with this string
*/

[outputFormatter release];
[myLocale release];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top