1

任务:显示一个 UIDatePicker 并抓取选定的日期,然后在标签中显示选定的日期(格式为日、月、年)。

目前的进展:

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

    date.text = message;
}

这将以 YYYY-MM-DD 23:20:11 +0100 的格式显示日期。我不想显示时间。我还想以不同的格式显示日期。

是否可以访问日期选择器的各个组件,即。日期选择器.month

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

4

4 回答 4

2

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

于 2010-07-05T23:48:56.217 回答
1

你要的是descriptionWithCalendarFormat:timeZone:locale:方法。请参阅Apple 对该方法的说明。

例如,要以 YYYY-MM-DD 格式显示日期,您可以使用:

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

我相信这里的格式字符串使用与 C 标准库中的 strptime 相同的标记,但是知道 Apple 可能会有一些细微的差异。该格式的描述是here。

你也可以使用 NSDateFormatter 类的stringFromDate: 方法。 它使用不同的格式(Unicode 格式)。我相信这是在 Objective C 中格式化日期字符串的“首选”方式,但使用起来可能也有点复杂。

最后,请参阅此 SO question以获取有关提取单个 NSDate 组件的信息。

希望有帮助。

于 2010-07-05T23:25:08.970 回答
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);
于 2012-03-03T07:08:16.373 回答
0

Datepicker 是一个特殊情况的 uipickerview,因此您可能能够获取每个组件中的值,但我不在 Xcode 面前验证这一点。

但是,您可以使用 NSDateFormatter 将返回给您的 nsdateformatter 更改为您正在寻找的任何格式。

于 2010-07-05T23:22:38.267 回答