I have a NSString that keeps date:
1900-01-01T11:00:00
I need to format it, so I have a formatter:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"dd/MM/yyyy hh:mm:ss a"];
How to format this string now?
NSString* formatedDateString = [df ???];
example for getting current date :
You need to create two date formatter, one for parsing, one for formatting; Your parsing format is "yyyy-MM-ddThh:mm:ss" and your output format is "dd/MM/yyyy hh:mm:ss a". So, something like this :
Create a date formatter, that returns a date object for for the given string, create a second date formatter, that returns a string in the desired format from that date.
But you could also let the output date formatter decide the style in respect to the locale:
for a american locale, you should now cat the desired format.
if you want to enforce format "dd/MM/yyyy hh:mm:ss a" for the user, you should also set the locale of the output date formatter.
a complete command line example.
If you dont set the locale like
[outputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
it will lead do a ugly mix of formats with user's sefault locale, if it not happend to be 'en_US'ie in German:
31/12/2012 02:00:00 nachm.
This is a format not used in german.To support user's language and locale you should instead use the different styles.
The q&a rmaddy provided indicates, that there are rare cases, where the parse format gets rewritten. To avoid this, set the input formatted's format to a certain locale, like
[inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];