Chris Loonam
Chris Loonam

Reputation: 5745

NSDateFormatter dateFromString incorrect

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?

Upvotes: 2

Views: 90

Answers (2)

slxl
slxl

Reputation: 689

Instead of @"hh:mm a MM/dd/YYYY" formatter try to use @"hh:mm a MM/dd/yyyy".

According to the Apple's docs:

"A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year."

https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html#//apple_ref/doc/uid/TP40002369-SW1

Upvotes: 2

Rob
Rob

Reputation: 437552

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

Upvotes: 1

Related Questions