Reputation: 1004
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
Upvotes: 2
Views: 2627
Reputation: 57169
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)
Upvotes: 8
Reputation: 69469
Lowercase mm
is for minutes not months, month use uppercase MM
:
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd";
NSDate *cDate = [formatter dateFromString:thisLine];
NSLog(@"cDate '%@' thisLine '%@'", cDate, thisLine);
Upvotes: 12