tags:

views:

42

answers:

2

I've probably overlooked something simple, but I can't figure out how to convert a specific date format in Objective-C. I'm receiving dates in this format:

Sun, 10 Oct 2010 01:44:00 +0000

And I need to convert it to a long format with no time, like this:

October 10, 2010

I've tried using NSDateFormatter, but when I try to get a date from the string, it always comes back nil. I've tried it this way:

NSString *dateFromData = [articleData objectAtIndex:5];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];

[dateFormatter setDateStyle:NSDateFormatterLongStyle];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
NSDate *date = [dateFormatter dateFromString:dateFromData];  

NSString *formattedDateString = [dateFormatter stringFromDate:date];

The date string always comes back nil. Am I missing something simple here?

A: 

The problem is you need to use two date formatters. One to parse the original format and one to produce the desired output. You also can't use the LongStyle date format as it doesn't match your input style.

NSDateFormatter *df = [[NSDateFormatter alloc] initWithDateFormat:@"%a, %d %b %Y %H:%M:%S %z"
                                             allowNaturalLanguage:false];
NSDate *d = [df dateFromString:@"Sun, 10 Oct 2010 01:44:00 +0000"];
NSDateFormatter *df2 = [[NSDateFormatter alloc] initWithDateFormat:@"%B %d, %Y"
                                              allowNaturalLanguage:false];
[df2 stringFromDate:d]

(Note, I wrote this code in MacRuby and ported it back to Objective-C so there maybe syntax errors.)

irb(main):001:0> df = NSDateFormatter.alloc.initWithDateFormat("%a, %d %b %Y %H:%M:%S %z", allowNaturalLanguage:false)
=> #<NSDateFormatter:0x20021b960>
irb(main):002:0> d = df.dateFromString("Sun, 10 Oct 2010 01:44:00 +0000")
=> #<NSCalendarDate:0x2002435e0>
irb(main):004:0> df2 = NSDateFormatter.alloc.initWithDateFormat("%B %d, %Y", allowNaturalLanguage:false)
=> #<NSDateFormatter:0x20026db60>
irb(main):005:0> df2.stringFromDate(d)
=> "October 09, 2010"
dj2
@dj2 this code does not work, the first date format is incorrect
Aaron Saunders
The formatter works form me. Added the macirb session output.
dj2
A: 

This is the code I got to work, couldn't get the other format string to function

NSString *dateFromData = @"Sun, 10 Oct 2010 01:44:00 +0000";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, dd MMM yyyy hh:mm:ss zzzz"];

NSTimeZone *gmt = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
[dateFormatter setTimeZone:gmt];

NSDate * date = [dateFormatter dateFromString:dateFromData];

[dateFormatter setDateStyle:NSDateFormatterLongStyle];

NSString *formattedDateString = [dateFormatter stringFromDate:date];
Aaron Saunders