I have tested my app with regiorn format USA and the date display is correct. When region changed to Italy where I live now contains null value.
My starter string date is: - "May 2, 2013 6:46:33 PM"
The result date correct is: - "02/05/2013 18:46:33"
Here my code:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter setDateFormat:@"MM dd, yyyy hh:mm:ss a"];
NSDate *dateFromString;
dateFromString = [dateFormatter dateFromString:dataStr];
[dateFormatter setDateFormat:@"dd/MM/yyyy HH:mm:ss"];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
NSString *stringFromDate = [dateFormatter stringFromDate:dateFromString];
If your starter string is May 2, 2013 6:46:33 PM
then you have two issues:
MM dd, yyyy hh:mm:ss a
does not match your string. It needs to be MMMM dd, yyyy hh:mm:ss a
. The use of MM
is for numeric months. Use MMM
for abbreviated month names and use MMMM
for full month names.Your code should be:
NSString *dateStr = @"May 2, 2013 6:46:33 PM";
NSDateFormatter *inputDateFormatter = [[NSDateFormatter alloc] init];
[inputDateFormatter setDateFormat:@"MMMM dd, yyyy hh:mm:ss a"];
[inputDateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
NSDate *dateFromString = [inputDateFormatter dateFromString:dataStr];
NSDateFormatter *outputDateFormatter = [[NSDateFormatter alloc] init];
[outputDateFormatter setDateFormat:@"dd/MM/yyyy HH:mm:ss"];
NSString *stringFromDate = [outputDateFormatter stringFromDate:dateFromString];