2010-07-05 70 views
1

任务:显示UIDatePicker并抓取选定日期,然后在标签中显示所选日期(格式为日,月,年)。iPhone日期选择器,如何访问单个项目

最新研究进展:

-(IBAction)pressButton:(id)sender 
{ 
    NSDate *selected = [datePicker date]; 
    NSString *message = [[NSString alloc] initWithFormat:@"%@", selected]; 

    date.text = message; 
} 

这将显示在YYYY-MM-DD 23点20分十一秒+0100格式的日期。我不想显示时间。我也想以不同的格式显示日期。

是否有可能访问日期选择器的单个组件,即。 datePicker.month

任何解决方案或链接非常感谢。

回答

1

你想要的是descriptionWithCalendarFormat:timeZone:locale:方法。见Apple's description of the method.

例如,显示在刚刚YYYY-MM-DD格式的日期,你会使用:

NSString *message = [selected descriptionWithCalendarFormat: @"%Y-%m-%d" timeZone: nil locale: nil] 

我相信这里的格式字符串使用相同的标记为从C strptime标准库,但可能会有一些小的差异,知道苹果。该格式的说明是here.

您也可以使用NSDateFormatter类'stringFromDate: method.它使用不同的格式(Unicode格式)。我相信这是在Objective C中格式化日期字符串的“首选”方式,但它的使用可能也更复杂一些。关于提取单个NSDate组件的信息,请参阅this SO question

希望有所帮助。

+0

非常感谢所有的答案,使用这一行,并得到它全部排序。 – 2010-07-06 22:40:44

+0

既然您发现此答案有帮助,您可以对其进行修改并/或将其标记为正确以便其他用户使用:) – 2010-10-04 15:25:42

0

Datepicker是一个特殊情况的uipickerview,所以你可能能够获得每个组件的值,但我不在Xcode之前来验证。

然而,您可以使用NSDateFormatter将nsdateformatter更改为您正在查找的任何格式。

2

如果您正在讨论访问日期选择器的各个组件,则不能。 UIDatePicker不会从UIPickerView继承,所以它们没有API。但是,文档确实声明UIDatePicker“将自定义选取器视图对象作为子视图”,这意味着您可以遍历UIDatePicker的子视图直到找到UIPickerView。请注意,这是非常危险的,但是。

+0

OP要求的是日期的组件,即日,月,年。您可以使用[UIDatePicker date]从UIDatePicker获取日期,然后使用NSDateComponents从中获取单个组件。 – 2010-07-06 16:18:58

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);