Error when converting date string to NSObject - objective-c

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

Related

adding 0 in front of nsnumber

I'm trying to save a month and the format needs to be 2 digits. The problem is the xcode is converting every month below October to 1 digit. How can I format the number so that it will be for example 01 for January?
Edit saving as a nsnumber. This is for an HTTP request call to stripe. The date that gets sent keeps changing from 0X to X for all months before October.
Edit 2 I'm also getting the following warning from where I convert the stripe card to a nsnumber
Implicit conversion loses integer precision:'NSUInteger' (aka 'unsigned long') to 'int'
Edit 3 To clarify, the number 01 keeps getting changed to 1. I want to save it as 01. How do I change the format of the number?
You could use either string formatting, or a number formatter. Either way, the output is going to be a string since you can't format the number its self. Here's an example:
NSNumber *number = #(9);
// using a number formatter
NSNumberFormatter *formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle:NSNumberFormatterNoStyle];
[formatter setMinimumIntegerDigits:2];
NSString *numberString = [formatter stringFromNumber:number];
NSLog(#"%#",numberString);
// using string formatters
numberString = [NSString stringWithFormat:#"%02ld",(long)[number integerValue]];
NSLog(#"%#",numberString);

Adding an object to NSMutableArray causing crash

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

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.

How do you convert date time including milliseconds and timezone info to NSDate

I'm trying to convert a string to an NSDate,
however the format always comes out as nil
The date I'm trying to convert is:
2012-08-16T16:20:52.619000+00:00
The date format I'm trying is:
#"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZ"
If I change the date to:
#"2012-08-16T16:20:52.619000+0000" // removing the : from +00:00
it works a treat, however I would
(I have also tried
#"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZ:ZZ"
#"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZ':'ZZ"
but that didn't work either).
Is it even possible to do this without doing string manipulation and removing the final ":"?
I did a final search around this and found out that you have to use
getObjectValue
rather than
dateFromString
In case someone else runs in to this issue, I post my method for converting such strings to NSDate
+ (NSDate *)dateFromString:(NSString *)dateString {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZ"];
NSDate *theDate = nil;
NSError *error = nil;
[dateFormat getObjectValue:&theDate forString:dateString range:nil error:&error];
[dateFormat release];
return theDate;
}
It looks like you are using ISO 8601 formatted dates. If you are getting these from a web service, the format changes according to the format. Check this out:
http://boredzo.org/iso8601parser/
This will convert dates according to the format, and even when the format changes slightly.
How about something like
[formatter setDateFormat:#"yyyy-MM-dd'T'HH:mm:ss'Z'"];
the Z has to be in single quotes.

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.