Mark Struzinski
Mark Struzinski

Reputation: 33471

How to Format Unknown Date Format in Objective-C

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?

Upvotes: 1

Views: 1123

Answers (2)

Aaron Saunders
Aaron Saunders

Reputation: 33335

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];

Upvotes: 1

dj2
dj2

Reputation: 9620

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"

Upvotes: 0

Related Questions