Reputation: 906
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.
Upvotes: 0
Views: 60
Reputation: 16976
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
.
Upvotes: 1