Adding an object to NSMutableArray causing crash - objective-c

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

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

Related

Error when converting date string to NSObject

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

showing a null value in NSdateformatter

From the the log start time value is printed. why end time showing (null) value.
NSString *start=#"00:01:00";
NSString *end=#"24:00:00";
NSDateFormatter *formatter1 = [[NSDateFormatter alloc] init];
[formatter1 setDateFormat:#"HH:mm:ss"];
NSDate *end1=[[NSDate alloc]init];
end1=[formatter1 dateFromString:end];
NSLog(#"end1:%#",end1);
**Log print - end1:(null)**NSDate *start1=[[NSDate alloc]init];start1=[formatter1 dateFromString:start];NSLog(#"start1:%#",start1);**Log print - start1:1999-12-31 18:31:00 +0000**
The hour value must be within 0 and 23, so 24 is an invalid hour value even for a 24hour date formatter. See http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns for valid values and formatters.
Since 24 as hour is invalid, the formatter returns nil . In your case you would need to add the date to achieve start 00:01:00 and end 00:00:00 which is the beginning of the next day.
Use
NSString *end = #"00:00:00";
instead of
NSString *end = #"24:00:00";

parsing date from string, nsdate, objective c

Below is a string represented a date
NSString *dateStr = #"2011-07-06";
And when I am trying to convert it to NSDate by doing :
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd"];
NSDate *tmp = [format dateFromString:dateStr];
NSLog(#"tmp is %#",[tmp description]);
What I am getting from the console is
tmp is 2011-07-06 04:00:00 +0000
I dont understand why I am getting extra info :04:00:00 +0000 for the result
Please help if you experienced it before
Your code
NSString *dateStr = #"2011-07-06";
NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:#"yyyy-MM-dd"];
NSDate *tmp = [format dateFromString:dateStr]
will result in a NSDate object, that represents your local time at 0:00 — the beginning of the day.
but if you print a plain date object, it will result in a string that represents the time in GMT timezone, as internally all dates are normalized to that timezone.
As your string is 4 hours ahead, we can tell, that you most likely are in East Europe, maybe Moscow.
So if you want to see the string in your timezone, you need to use a NSDateFormatter to create it from the date object.
NSLog(#"tmp is %#",[formatter stringFromDate:tmp]);
to check, if it is correct, what I said, change the format to contain the time components.
formatter.format = [#"yyyy-MM-dd HH:mm"];
NSLog(#"tmp is %#",[formatter stringFromDate:tmp]);
The formatter will also take "oddities" like Leap Day, Leap Month (yes — those exits), Daylight Saving Times, Leap Seconds … in account — accordantly to the current calendar.
A great WWDC 2011 Video: Performing Calendar Calculations — a must-see for every cocoa developer.
BTW: to print a object with NSLog you dont need to call -description on it to pass in a string. NSLog will do this internally.
NSLog(#"tmp is %#", tmp);
is just fine.
The answer is simple, NSLog just converts the NSDate to a NSString, using its formatter with GMT (zero) timezone.
Your formatter is by default set to your default time zone, which is probably -4:00. When you print it out, NSLog converts it to 0:00, adding 4 hours.
In general, it's unsafe to parse dates without specifying their timezone.

NSDateFormatter Bug : incorrect string to date conversion

I have an a string in UTC which i want to convert to NSDate. Somehow Im getting 30 minutes error
The string is
2012-04-10T00:00:00+05:30
the converted date is
2012-04-09 19:00:00 +0000
where as it should have been
2012-04-09 18:30:00 +0000
Im using this function to convert string to date
- (NSDate *)parseRFC3339Date{
NSDateFormatter *rfc3339TimestampFormatterWithTimeZone = [[NSDateFormatter alloc] init];
[rfc3339TimestampFormatterWithTimeZone setDateFormat:#"yyyy-MM-dd'T'HH:mm:ssZ"];
NSDate *theDate = nil;
NSError *error = nil;
if (![rfc3339TimestampFormatterWithTimeZone getObjectValue:&theDate forString:self range:nil error:&error]) {
NSLog(#"Date '%#' could not be parsed: %#", self, error);
}
[rfc3339TimestampFormatterWithTimeZone release];
return theDate;
}
If you were to create an NSRange covering the whole of the string and passed its address in to -getObjectValue:forString:range:error:, then you'd see that on output it would be short. Parsing stopped at the colon because the 'Z' in the format string only matches something like "-0800" (no colon). If you were to specify 4 Zs, 'ZZZZ', it would match something like "GMT-08:00". That allows a colon, but requires "GMT". You can try inserting the "GMT" if you're sure of the format of your date string.
I ran into ISOdateFormatter here http://boredzo.org/iso8601unparser/ which works perfectly. Fund it better than modifying incoming date strings.

Know if a date(weekday) is bettween two other dates(weekedaysº)

Im trying to know if the current day of the week + and hour is in between of 2 other weekday + hour.
Let's say, right now is "Tuesday 16:26" and there is an interval that starts with "Tuesday 16:00" and "Tuesday 22:00" so it should return YES.
Im creating dates from the previous strings, and this function tells me if it's in the interval.
This function is part of a class, whose attributes "fechaInicio" and "fechaFin" are start date and end adate respectively.
- (BOOL)dateInInterval:(NSDate *)testDate {
// date1 is the instance variable containing the starting date
// date2 is the instance variable containing the ending date
NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:#"en"] autorelease]];
[dateFormatter setDateFormat:#"EEEE HH:mm"];
NSString *dateString = [dateFormatter stringFromDate:self.fechaInicio];
NSLog(#"La fecha es: %#", dateString);
dateString = [dateFormatter stringFromDate:self.fechaFin];
NSLog(#"La fecha es: %#", dateString);
NSLog(#"time interval nicio: %d", [testDate timeIntervalSinceDate:self.fechaInicio]);
NSLog(#"time interval fin: %d", [testDate timeIntervalSinceDate:self.fechaFin]);
return ([testDate timeIntervalSinceDate:self.fechaInicio] > 0 &&
[testDate timeIntervalSinceDate:self.fechaFin] < 0);
}
The thing is that in never returns YES, even though I can see the date is in the interval. Im afraid how Im turning the string to date. I input "Tuesday 16:00" what year is it, what month, if I format the actual date to "EEEE HH" will it save the month and year?
Thanks
For your case, I'd advice to find some fixed known date for Monday and apply the full date for each EEEE HH:mm string. This will give correct values inside date and i think your logic will start working