user979331 user979331 - 1 year ago 106
Objective-C Question

Change date string format

I have a date string like so:

22-04-2016 8:00:00 AM

How do I change the format to
04-22-2016 8:00:00 AM

I have tried the following:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"MM-dd-yyyy"];

NSLog(@"%@", [dateFormat dateFromString:[cell scheduledDate]]);

but this returns
. How can I change the format of this string?
[cell scheduledDate]
is a string.

Answer Source

You can say something like:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
//Set the AM and PM symbols
[dateFormatter setAMSymbol:@"AM"];
[dateFormatter setPMSymbol:@"PM"];
[dateFormatter setDateFormat:@"dd-MM-yyyy h:mm:ss a"]; 
NSDate *currentDate = [dateFormatter dateFromString:[cell scheduledDate]];

To get it to an NSDate. Then as matt suggests use another NSDateFormatter to get it to a different string. I agree with his objection but perhaps it is not possible to maintain the information as a date.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download