While working on a date picker control I encountered a problem, where I was supposed to set year of the date picker control to a specific year. For this problem, I added a custom text box over date picker. When a user enters a year in that text box and clicks done button, I changed the year of date picker to the year provided in text box.

Here is the piece of code, which I used to change year of my date picker control. This logic can be used to change other components of the date picker with any year, month or date.

Code:
NSDate *today=calenderPicker.date;
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *components = [gregorian components: (NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit) fromDate: today];
components.year = [textField.text intValue]; // Here value for year is fetched from a text field control. Similarly other values like month, date, hour or minute can be changed.
[calenderPicker setDate: [gregorian dateFromComponents:components] ]; // Update the date picker control.
[gregorian release];

Enjoy!


4 thoughts on “How to set specific year/month/date/time into UIDatePicker control

    1. @google-eb79f4befdf1a1b042a09452813dcb24:disqus if you are talking about the attached image, then it’s just for illustration. If you are not able to get the code, then here’s the explanation:
      given code sets year to the picker (components.year = [textField.text intValue];). Similarly you can set other components, like month, date and time.

Leave a Reply

Your email address will not be published. Required fields are marked *