views:

84

answers:

3

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.

A: 

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.

AtomRiot
A: 

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.

Mitch Lindgren
Thank you very much to all answers, used this line and got it all sorted.
Skream
Since you found this answer helpful, you can upvote it and/or mark it correct for the benefit of other users :)
Mitch Lindgren
+2  A: 

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.

Saurabh Sharan
What the OP wants is the components of the date, ie day, month, year. You can get the date from the UIDatePicker using [UIDatePicker date] and then get individual components from that using NSDateComponents.
Mitch Lindgren