Question

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];
Was it helpful?

Solution

If your starter string is May 2, 2013 6:46:33 PM then you have two issues:

  1. Your format string 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.
  2. Your date string has month names in English. If your device is setup for Italy then it won't properly parse the month names since it will expect the months names to be in Italian.

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];

OTHER TIPS

Use this:

NSDate* sourceDate = your_date
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];

NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;

NSDate* destinationDate = [[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate];

Hope it helps you.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top