Home > iPhone > Parse Date from RSS to NSDate

Parse Date from RSS to NSDate

December 26th, 2008

Today I’ll show how to parse date from RSS feed to NSDate in iPhone application.

When processing several RSS feeds, it is usual task to arrange and sort them by date. Therefore text representation of date need to be transformed to NSDate.

My googling of solutions for this issue resulted in use of [NSCalendarDate dateWithNaturalLanguageString:string] function. As I wrote before, NSCalendarDate is not supported under iPhone OS, so this way lacks.

Another way is to parse date via NSDateFormatter, but I didn’t find any full solution. So let’s write it :)

Usually RSS date is stored in following format: @"Fri, 12 Dec 2008 18:45:15 -0800" (to learn more about RSS spec, use this resource: RSS 2.0 Specification). In date formatter terms it can be written as @"EEE, d MMM yyyy HH:mm:ss Z". Knowing that, it is easy to write result code. Here it is:

NSString *string = @"Fri, 12 Dec 2008 18:45:15 -0800";
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"EEE, d MMM yyyy HH:mm:ss Z"];
NSDate *date = [dateFormatter dateFromString:string];
// if (date == nil) { } - uncomment this if you want to handle failures
[dateFormatter release];

I’m not sure this covers all of situations, but it is a good point to start from :)

iPhone , ,

  1. No comments yet.
  1. No trackbacks yet.