saman01 saman01 - 2 months ago 6
Objective-C Question

dateFromString returns the wrong date

I have the following code:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-mm-dd";
NSDate *cDate = [formatter dateFromString:thisLine];
NSLog(@"cDate '%@' thisLine '%@'", cDate, thisLine);


NSLog prints:
cDate '2011-01-10 05:07:00 +0000' thisLine '2011-07-10'
while cDate should be '2011-07-10'

Any thoughts?

Thanks

Joe Joe
Answer

The NSDate description will always print the date with its own formatting, generally for the +000 time zone. You need to use the date format to get the correctly formatted date and use MM for month not mm.

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd";
NSDate *cDate = [formatter dateFromString:thisLine];
NSLog(@"cDate '%@'  thisLine '%@'", [formatter stringFromDate:cDate], thisLine);

-(NSString*)description
Discussion
The representation is not guaranteed to remain constant across different releases of the operating system. To format a date, you should use a date formatter object instead (see NSDateFormatter and Data Formatting Guide)

Comments