1

In my app, I get data from Webservices. The data comes in form of a XML and I use a parser to parse and get the data I need.

In one of the result, I get the date as 14 DEC 2011. However I would like to display the date as 2011-14-12.

Here is the code I use..

NSDate *endDate = [CommonHelper getDateFromString:[NSString stringWithString:elementValue] :@"dd-MMM-yyyy HH:mm:ss"];

+ (NSDate *) getDateFromString: (NSString *) dateStr: (NSString *) format
{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:format]; 
    NSDate *newDate = [dateFormat dateFromString:dateStr];
    [dateFormat release];

    return newDate;
}

Would someone be able to help me with how I can do this?

learner2010
  • 4,157
  • 5
  • 43
  • 68
  • Use NSDateFormatter to convert the date string to an NSDate object, then use NSDateFormatter again to convert the NSDate object into the desired format. – Hot Licks Jan 03 '12 at 19:48
  • thanks for the reply.. I did try to convert that date to NSDate.. however, it does not seem to convert properly cause I get null value ... – learner2010 Jan 03 '12 at 19:55
  • If you get the date as "14 DEC 2011" you may have to try using the formatting "dd MMM yyyy". Also, I recommend you to set a Locale, otherwise the parsing may depend on the user local setting. – seppo0010 Jan 03 '12 at 20:09
  • thanks for the reply.. could you explain what you mean by setting a locale? – learner2010 Jan 03 '12 at 20:55

1 Answers1

1

Use these methods for parsing the date string and formatting the date object as you described:

+ (NSDate *)parseDate:(NSString *)dateString {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"dd MMM yyyy"]; 
    NSDate *newDate = [dateFormat dateFromString:dateString];
    [dateFormat release];

    return newDate;
}

+ (NSString *)formatDate:(NSDate *)date {
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"yyyy-dd-MM"]; 
    NSString *dateString = [dateFormat stringFromDate:date];
    [dateFormat release];

    return dateString;
}
Hejazi
  • 16,587
  • 9
  • 52
  • 67
  • 1
    As seppo0010 suggests, you should [ALWAYS set the locale](http://stackoverflow.com/questions/6613110/what-is-the-best-way-to-deal-with-the-nsdateformater-locale-feature). – Hot Licks Jan 03 '12 at 20:39