9.13.2012

String Representation of Date from UIDatePicker

In iOS, there's this UI element that allows the user to select the date and time. This is called the Date Picker.

Here's a way of getting the text from the iOS' Date Picker:


/*_datePicker is the current UIDatePicker object. Set the mode of the date picker. In this example, setting the time is disabled.*/
[_datePicker setDatePickerMode:UIDatePickerModeDate];
/*Initialize a NSDateFormatter object. This object will get the string representation of the NSDate object.*/
_dateFormatter = [[NSDateFormatter alloc] init];
/*Set the locale of the NSDateFormatter object.*/
NSLocale *locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_EN"] autorelease];
[_dateFormatter setLocale:locale];
/*Set the date style and the time style of the formatter. Note that the next two lines of code are important. Without them, when NSDateFormatter's instance function/method - stringFromDate: is used, the returned string is empty. It is not stated in the NSDateFormatter class reference that the default value of dateStyle and timeStyle are set to NSDateFormatterNoStyle but I think they are.*/
[_dateFormatter setDateStyle:NSDateFormatterLongStyle];
[_dateFormatter setTimeStyle:NSDateFormatterNoStyle];

...

/*This is the code for getting the string representation of the selected date*/
NSString *selectedDate = [_dateFormatter stringFromDate:_datePicker.date];


Note: Automatic Reference Counting (ARC) is not used in this example.

No comments:

Post a Comment