NSDateFormatter incorrect dateFromString

advertisements

I am setting the value of a UITableViewCell's detailTextLabel to the current date and am then allowing the user to modify that date using a UIDatePicker. I set the text label like this

NSDate *currentDate = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a MM/dd/YYYY"];
cell.detailTextLabel.text = [dateFormatter stringFromDate:currentDate];

This sets the text label properly, and it displays something like 08:20 AM 08/07/2015. This is the desired output. When the user selects this cell, I want the date property of my date picker to be set to the date displayed in the cell. To implement this, I have the following in my tableView:didSelectRowAtIndexPath: method

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"hh:mm a MM/dd/YYYY"];

NSString *dateString = [tableView cellForRowAtIndexPath:indexPath].detailTextLabel.text;
self.datePicker.date = [dateFormatter dateFromString:dateString];

However, rather than setting the date to the one that is in the cell, this sets the date of the picker to 08:20 AM 12/21/2014, which is not what it should be. Logging dateString outputs the correct string that is in the table view cell.

Is there a reason that I am experiencing this issue?


The year portion of your formatter string should be yyyy, not YYYY.