1

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.

Andrew Davis
  • 2,310
  • 1
  • 24
  • 43

4 Answers4

2

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 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 Jul 06 '10 at 16:18
1

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.

Community
  • 1
  • 1
Mitch Lindgren
  • 2,120
  • 1
  • 18
  • 36
1
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);
Ajumal
  • 1,048
  • 11
  • 33
divakar
  • 57
  • 8
0

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
  • 1,869
  • 3
  • 18
  • 24