tags:

views:

440

answers:

1

I need to be able to format an existing NSString into a different date format. NSDateFormatter has dateFromString and stringFromDate methods, but no stringFromString. Is it possible to take a date that I have in the form of an NSString and reformat it using something similar to:

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    strMyDate = [dateFormatter stringFromString(does not exist):strMyDate];
+9  A: 

You need to create a date from the string, then reformat that date into a different string.

Something like:

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];

// get NSDate from old string format
[dateFormatter setDateFormat:@"yyyy-MM-dd"];
NSDate *date = [dateFormatter dateFromString:@"2009-03-18" ];

// get string in new date format
[dateFormatter setDateFormat:@"dd-MM-yyyy"];
NSString *strMyDate= [dateFormatter stringFromDate:date];
Andrew Grant