-4

I am trying to combine a string date and time then convert that to an NSDate. My code is:

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];

The output to the log of prayerDateAndTime is 2013-07-08 20:26:00 +0000 as expected and the error message is Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSArrayM insertObject:atIndex:]: object cannot be nil'.

It crashes at the [arrayOfDatesAsDates addObject:prayerDateAndTime]; line.

Why is this?

Many thanks

CodaFi
  • 43,043
  • 8
  • 107
  • 153
samiles
  • 3,768
  • 12
  • 44
  • 71

1 Answers1

1

It looks like [dateAndTimeFormatter dateFromString:@"2013-07-08 20:26:00 +0000"] is returning nil because your date string "2013-07-08 20:26:00 +0000" does not match your dateFormat: @"dd-MM-yyyy HH:mm" ... try running after replacing:

[dateAndTimeFormatter setDateFormat:@"dd-MM-yyyy HH:mm"]

with

[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

Format strings for Date Formats given here: http://www.unicode.org/reports/tr35/tr35-25.html#Date_Field_Symbol_Table

Timezone string acquired from: https://stackoverflow.com/a/3299389/2022405

Community
  • 1
  • 1
George Mitchell
  • 1,158
  • 2
  • 11
  • 24