-4

我正在尝试组合字符串日期和时间,然后将其转换为 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];

为什么是这样?

非常感谢

4

1 回答 1

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

时区字符串来自:https ://stackoverflow.com/a/3299389/2022405

于 2013-07-08T20:52:27.653 回答