2
votes

I've one problem with NSDate and NSDateFormatter.

From this NSString

NSString *startDate = @"Thu, 19 Apr 2012 13:09:56 +0000";

I would obtain a date localized with current locale like this "Thu, 19 Apr 2012 13:09". I've elaborate this code but the 'endDate' string return nil (within the debugger obtain 'invalid CFStringRef').

[NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
NSDate *dateFromString = [dateFormatter dateFromString:startDate];

[dateFormatter setDateFormat:@"EEE dd MMM yyyy HH:mm"];
[dateFormatter setLocale:[NSLocale currentLocale]];

NSString *endDate = [dateFormatter stringFromDate:dateFromString];

Where is the bug?

Alex.

2
I just tried your code, and it worked like a charm.. So not sure why you get an error? - Krueger
Make sure you're getting a valid NSDate. - Hot Licks

2 Answers

2
votes

It seems that the code executed in a non-US locale. I use non-US locales. I have the same nil output also.

It seems like we need to setLocale: before setDateFormat:.

Below code works ok:

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
NSLocale *usLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease];
[dateFormatter setLocale:usLocale];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy HH:mm:ss ZZZ"];
0
votes

Ya its working correctly..Try removing autorelease from your dateFormatter and then try it again.

And i hope this link is same as yours

Invalid CFStringRef issue

Try this answer and change your format option with "ZZ" and not "ZZZ".