I'm sending details to a server which requires that I convert a date string into an NSDate object. The dictionary that will carry this object is declared like this
NSMutableDictionary *detailsRequest = [NSMutableDictionary dictionary];
Then the code which converts the date string to an object looks like this
[_dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]];
[_dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZZZ"];
[_dateFormatter setAMSymbol:@"am"];
[_dateFormatter setPMSymbol:@"pm"];
[detailsRequest setObject:[_dateFormatter stringFromDate:[_dateFormatter dateFromString:val]] forKey:NDUserServerDateOfBirthKey];
The key NDUserServerDateOfBirthKey is declared as a constant like this
NSString * const NDUserServerDateOfBirthKey = @"dob";
The value for val is always '09/08/1987' and when it hits the last line it throws a SIGABRT error which says
2018-08-23 10:33:04.612769+0100 ClientCore[353:36543] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSDictionaryM setObject:forKey:]: object cannot be nil (key: dob)'
I've tried reducing the _dateFormatter to just [_dateFormatter setDateFormat:@"yyyy-MM-dd"]; but it still crashes with the same error. My string date always has a value so what is it I'm doing wrong?
The error occurs because the date format is wrong and the date string cannot be converted.
Please try to understand the format. The date string contains day (d), month (M) and year (y) slash separated – or month (M), day (d) and year (y) - but there is no letter T
, no hyphens (-), no hours (H), no minutes (m), no seconds (s), no milliseconds (S), no timezone (Z) and no am/pm
The format is @"dd/MM/yyyy"
or @"MM/dd/yyyy"
And why are you converting string to date and then immediately back to string?
If you want to convert dd/MM/yyyy
to ISO8601 you need two different formats for input and output
NSString *val = @"09/08/1987";
NSDateFormatter *_dateFormatter = [[NSDateFormatter alloc] init];
_dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
_dateFormatter.dateFormat = @"dd/MM/yyyy";
NSDate *date = [_dateFormatter dateFromString:val];
_dateFormatter.dateFormat = @"yyyy-MM-dd'T'HH:mm:ssZZZ";
NSString *convertedString = [_dateFormatter stringFromDate:date];