Reputation: 5754
I am trying to convert a string to date, my string is Sunday, November 24, 2020 @ 5:00 PM and is of date format EEEE, MMMM dd, YYYY @ hh:mm a
I am writing below code for the same but date is returning nil with this format and date. When I am removing Day and EEEE from format, it is working fine.
NSDateFormatter * dateFormatter = [NSDateFormatter new];
NSLocale * locale = [[NSLocale alloc] initWithLocaleIdentifier:@"de_LU"];
[dateFormatter setDateFormat:@"EEEE, MMMM dd, YYYY @ hh:mm a"];
[dateFormatter setLocale:locale];
NSDate *date = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@", @"Sunday, November 24, 2020 @ 5:00 PM"]];
//This line returning nil and assigning into date object
NSString * dateString = [dateFormatter stringFromDate:date];
NSLog(@"%@", dateString);
Can anyone help me with this?
Thanks in advance.
Upvotes: 0
Views: 83
Reputation: 285069
First of all the year specifier is wrong, it must be yyyy
but this is irrelevant with regard to the issue. And Nov 24 2020 is Tuesday by the way (also irrelevant).
In German (not even in luxembourgian German) there is no Sunday
or Tuesday
, for the input string you have to set the locale to something in English for example generic en_US_POSIX
NSDateFormatter * dateFormatter = [NSDateFormatter new];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.dateFormat = @"EEEE, MMMM dd, yyyy @ hh:mm a";
NSDate *date = [dateFormatter dateFromString:[NSString stringWithFormat:@"%@", @"Tuesday, November 24, 2020 @ 5:00 PM"]];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"de_LU"];
NSString * dateString = [dateFormatter stringFromDate:date];
NSLog(@"%@", dateString);
Upvotes: 1