views:

525

answers:

1

I have a novice question, will be happy if any one out there can help me.

I have an NSMutableArray, for example:

{
JobID = 109302930;
Subject = "Test Subject";
SubmitDate = "2009-09-15 17:27:34";
}

I am now trying to create sections in my table view and want to group my records based on "formatted" SubmitDate. For example;

16th May'09
===========
Item A
Item B

18th May'09
===========
Item C
Item G

20th May'09
===========
Item Z
Item K

I am creating this NSMutableArray with the following function (from an XML data source):

-(void)parser:(NSXMLParser *)parser didEndElement:(NSString *)elementName namespaceURI:(NSString *)namespaceURI qualifiedName:(NSString *)qName {   
    currentElement = [[NSString alloc] init];

    if ([elementName isEqualToString:@"subject"]) {
     [item setObject:currentSubject forKey:@"Subject"];
    } else if ([elementName isEqualToString:@"job_id"]) {
     [item setObject:currentJobID forKey:@"JobID"];
    } else if ([elementName isEqualToString:@"submit_date"]) {
     // I want to insert the date value in a formatted way instead of the standard MySQL date format (YYYY-MM-HH).
     [item setObject:currentJobSubmitDate forKey:@"SubmitDate"];
     [previewData addObject:item];
    }
}

As I commented in the above code, instead of YYYY-MM-DD HH:II:SS, I want to add the date as a formatted date string. How can I do that?

Thanks for your help.

+3  A: 

You'll want to use NSDateFormatter to do that. You can use it to create an NSDate, then use it again to create a differently-formatted string to use.

Jeff Kelley
Jeff, thanks. Yes, I tried that but didn't work. Using NSDateFormatter, I set the date format (Ex: yyyy-MM-dd) but I'm having problem on NSDate. I am unable to create an NSDate object with a string. Let's say I have an NSString and value is "2009-09-24 01:00:00".How can I create NSDate object based on this value? Sorry if this is a silly question, newbie here :)
TamTam
You'll need to follow four steps: 1.) Set your `NSDateFormatter`'s `dateFormat` property to what you currently have in string form. 2.) Use the `-dateFromString:` method of your `NSDateFormatter` to create an `NSDate` object from the string.3.) Set your `NSDateFormatter`'s `dateFormat` property to match what you want your string to look like in the end.4.) Use the `-stringFromDate:` method of your `NSDateFormatter` to create your string from your `NSDate`.
Jeff Kelley