我正在向服务器发送详细信息,该服务器要求将日期字符串转换为NSDate对象。像这样声明将携带该对象的字典
NSMutableDictionary *detailsRequest = [NSMutableDictionary dictionary];
然后将日期字符串转换为对象的代码如下所示
[_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];
键NDUserServerDateOfBirthKey声明为这样的常量
NSString * const NDUserServerDateOfBirthKey = @"dob";
val的值始终为'09 / 08/1987',当它到达最后一行时,会引发SIGABRT错误,提示
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)'
我尝试将_dateFormatter减少为[_dateFormatter setDateFormat:@“ yyyy-MM-dd”];但是它仍然崩溃并显示相同的错误。我的字符串日期总是有一个值,所以我在做什么错了?
答案 0 :(得分:0)
发生错误是因为日期格式错误,并且日期字符串无法转换。
请尝试了解格式。日期字符串包含以天(d),月(M)和年(y)斜杠分隔-或以月(M),天(d)和年(y)-但没有字母T
,没有连字符(-),无小时(H),无分钟(m),无秒(s),无毫秒(S),无时区(Z)和无am / pm
格式为@"dd/MM/yyyy"
或@"MM/dd/yyyy"
为什么将字符串转换为日期然后立即返回字符串?
如果要将dd/MM/yyyy
转换为ISO8601,则需要两种不同的输入和输出格式
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];