我正在尝试将字符串日期和时间组合,然后将其转换为NSDate。我的代码是:
NSMutableArray *arrayOfDatesAsDates = [[NSMutableArray alloc] init];
NSDateFormatter *dateAndTimeFormatter = [[NSDateFormatter alloc] init];
[dateAndTimeFormatter setLocale:enUSPOSIXLocale];
[dateAndTimeFormatter setDateFormat:@"dd-MM-yyyy HH:mm"];
NSLog(@"here");
//create an NSDate with todays date and the right prayer time
NSString *prayerDateString = [curDate stringByAppendingString: @" "];
prayerDateString = [prayerDateString stringByAppendingString: timeOfMagrib];
NSDate *prayerDateAndTime = [dateAndTimeFormatter dateFromString:prayerDateString]; //convert string back to date
NSLog(@"nsdate %@", prayerDateAndTime);
[arrayOfDatesAsDates addObject:prayerDateAndTime];
prayDateAndTime日志的输出是2013-07-08 20:26:00 +0000预期,错误消息为Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'
。
它在[arrayOfDatesAsDates addObject:prayerDateAndTime];
行崩溃。
为什么会这样?
非常感谢
答案 0 :(得分:1)
看起来[dateAndTimeFormatter dateFromString:@"2013-07-08 20:26:00 +0000"]
返回nil,因为您的日期字符串"2013-07-08 20:26:00 +0000"
与您的dateFormat: @"dd-MM-yyyy HH:mm"
不匹配...尝试在更换后运行:
[dateAndTimeFormatter setDateFormat:@"dd-MM-yyyy HH:mm"]
与
[dateAndTimeFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss ZZZ"]
// you really want this to match: 2013-07-08 20:26:00 +0000
// yyyy: 2013, four digit year
// MM: two digit numerical month
// dd: day of month
// HH: 24 hour hour
// mm: two digit minute
// ss: two digit second, zero padded
// ZZZ: time zone, {Z,Z,Z} -> RFC 822 GMT format
此处给出的日期格式的格式字符串: http://www.unicode.org/reports/tr35/tr35-25.html#Date_Field_Symbol_Table
获取的时区字符串