saman01
saman01

Reputation: 1004

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

Upvotes: 2

Views: 2627

Answers (2)

Joe
Joe

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

rckoenes
rckoenes

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

Related Questions