0

I have a function that takes 2 parameters, a date string in format @"2022-09-19T18:00:00.000Z", and a pattern (date format): @"MMM d".
The problem is that the date is always nil, therefore the formattedDate is nil as well, however, if i change the region in settings in my phone for US for example, the function works correctly.
Original region is Ukraine, but this should work in any region obviously.

{
  NSDateFormatter * df = [NSDateFormatter new];
  [df setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"];
  [df setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];

  NSDate * date = [df dateFromString: dateStr];
  [df setLocalizedDateFormatFromTemplate: pattern];
  [df setTimeZone:[NSTimeZone localTimeZone]];

  NSString * formattedDate = [df stringFromDate: date];

  if(formattedDate != nil){
    resolve(formattedDate);
  } else {
    resolve(@"");
  }
}

I've tried answers from there, but with no luck unfortunately.

Mod3rnx
  • 828
  • 1
  • 10
  • 21

1 Answers1

1

For fixed format date representations it's generally necessary to set the locale to POSIX:

RFC3339DateFormatter = [[NSDateFormatter alloc] init];
RFC3339DateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
RFC3339DateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZZZZZ";
RFC3339DateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];

If you're targeting macOS 10.12 or later you could also consider using NSISO8601DateFormatter.

sbooth
  • 16,646
  • 2
  • 55
  • 81
  • That partially fixes my problem, but locale is hardcoded for en_US, how can i set the user locale? I'm targeting IOS – Mod3rnx Sep 21 '22 at 20:33
  • I have figured out to use NSLocale currentLocale – Mod3rnx Sep 21 '22 at 20:52
  • If you're using a fixed format representation you want to use the POSIX locale almost always. – sbooth Sep 21 '22 at 21:20
  • I might not understand what you mean then. If i use en_US_POSIX, what do i do with other non en_US locales? – Mod3rnx Sep 21 '22 at 21:32
  • 1
    `-setDateFormat:` is for non-user visible fixed-format representations; fixed-format representations are by definition not localized and likely need the POSIX locale for consistent behavior. See https://developer.apple.com/library/archive/qa/qa1480/_index.html for additional information. On the other hand, `-setLocalizedDateFormatFromTemplate:` is meant for user-visible strings and should use the preferred locale for presentation. – sbooth Sep 21 '22 at 22:54