Search code examples
iosobjective-cios6

Setting 24 hour time in 12 hour UIDatePicker


So I've got an application in which some data is returned from a web service and a UIDatePicker is adjusted accordingly. The date is returned in the following format:

12-05-2013 16:05 (dd-mm-yyyy hh:mm)

The time is stored in 24 hour format, however the UIDatePicker is either 12 hour or 24 hour depending upon the settings on the device. The data comes in a JSON array and is the key potdd. The date picker I'm setting is called potddatepicker.

NSDateFormatter *inputFormat = [[NSDateFormatter alloc] init];
[inputFormat setDateFormat:@"dd-MM-yyy hh:mm"];
NSDate *inputDate = [inputFormat dateFromString: [jsonObjects objectForKey:@"potdd"]];

NSDate *potdd = inputDate;
[_potddatepicker setDate:potdd];

If the date is set before 12:00 then it works fine. If however the date is store in 24 hour time after 12 then it crashes with the following exception:

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: date'

I don't particularly want to force the time into 12 hour format just for the datepicker and then force it back into 24 hour when it comes out because in some locals it may be used in a 24 hour date picker. Anybody know how I can deal with this? I can't change the format that the time is stored in the database.

Thanks!


Solution

  • Your error has nothing to do with the date picker.

    You are using the wrong date format to parse the string. You need:

    [inputFormat setDateFormat:@"dd-MM-yyyy HH:mm"]; // HH is 24-hour, hh is 12-hour
    

    Also, since you are working with a fixed format, you should set the date formatter's locale to en_US_POSIX.