iPhone date picker, how to access individual items
Task: Show a UIDatePicker and grab the selected date, then 开发者_开发知识库display the selected date in a label (in the format of Day, Month, Year).
Current progress:
-(IBAction)pressButton:(id)sender
{
NSDate *selected = [datePicker date];
NSString *message = [[NSString alloc] initWithFormat:@"%@", selected];
date.text = message;
}
This will display the date in the format of YYYY-MM-DD 23:20:11 +0100. I do not want to display the time. I also want to display the date in a different format.
Is it possible to access the individual components of the date picker ie. datePicker.month
Any solutions or links is greatly appreciated.
If you're talking about accessing the individual components of the date picker, you can't. UIDatePicker doesn't inherit from UIPickerView, so they don't have API. However, the documentation does state that UIDatePicker "manages a custom picker-view object as a subview", which means you could traverse a UIDatePicker's subviews until you found a UIPickerView. Note that this is pretty risky, however.
What you want is the descriptionWithCalendarFormat:timeZone:locale:
method. See Apple's description of the method.
For instance, to display the date in just the YYYY-MM-DD format, you'd use:
NSString *message = [selected descriptionWithCalendarFormat: @"%Y-%m-%d" timeZone: nil locale: nil]
I believe the format string here uses the same tokens as strptime from the C standard library, but there may be some minor discrepancies, knowing Apple. A description of that format is here.
You could also use the NSDateFormatter class' stringFromDate: method. It uses a different format (the Unicode format). I believe it is the "preferred" way to format date strings in Objective C, but it's probably a bit more complicated to use as well.
Finally, see this SO question for information on extracting individual NSDate components.
Hope that helps.
NSDate *selected = [picker date];
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
//Set the required date format
[formatter setDateFormat:@"yyyy-MM-dd"]; //MM returns name of month small mm return the number.
//Get the string date
NSString* date = [formatter stringFromDate:selected];
//Display on the console
NSLog(@"%@",date);
Datepicker is a special case uipickerview so you might be able to get the value in each component but I am not in front of Xcode to verify that.
You could however use NSDateFormatter to change the nsdateformatter returned to you into whatever format you are looking for.
精彩评论