格式化时间日期选择器并在文本字段中显示时间

时间:2013-08-05 14:37:09

标签: objective-c uitextfield uidatepicker

我正在尝试在文本字段中的datePicker中显示时间。我已经走到了这一步

UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(112, 88, 97, 30)];
textField.borderStyle = UITextBorderStyleRoundedRect;
textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
textField.text=[NSString stringWithFormat:@"%@",[NSDate //what do I put here to put the datepicker time in the textfield]];
[self.view addSubview:textField];

UIDatePicker *datePicker = [[UIDatePicker alloc] init];
datePicker.datePickerMode = UIDatePickerModeDate;
[datePicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
datePicker.timeZone = [NSTimeZone defaultTimeZone];
datePicker.minuteInterval = 5;
datePicker.datePickerMode = UIDatePickerModeTime;

[textField setInputView:datePicker];

修改

我没有任何改变的价值,但这里是

-(void)datePickerValueChanged:(id)sender{


}

2 个答案:

答案 0 :(得分:4)

.h文件

@interface ViewController : UIViewController {
    UITextField *textField;
    UIDatePicker *dpDatePicker;
}

@end

.m文件

- (void)viewDidLoad {
    [super viewDidLoad];

    textField = [[UITextField alloc] initWithFrame:CGRectMake(112, 88, 250, 30)];
    textField.borderStyle = UITextBorderStyleRoundedRect;
    textField.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;

    [self.view addSubview:textField];

    dpDatePicker = [[UIDatePicker alloc] init];
    dpDatePicker.datePickerMode = UIDatePickerModeDate;
    [dpDatePicker addTarget:self action:@selector(datePickerValueChanged:) forControlEvents:UIControlEventValueChanged];
    dpDatePicker.timeZone = [NSTimeZone defaultTimeZone];
    dpDatePicker.minuteInterval = 5;

    [textField setInputView:dpDatePicker];
}

设置日期选择器值已更改方法以显示用户选择的值。

- (void)datePickerValueChanged:(id)sender {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"h:mm a"];
    textField.text = [dateFormatter stringFromDate:dpDatePicker.date];
}

答案 1 :(得分:3)

使用NSDateFormatter的{​​{1}}方法,如下所示:

stringFromDate:

您可以找到NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setDateStyle: NSDateFormatterShortStyle]; //Choose the appropriate style for your case textField.text = [dateFormatter stringFromDate:datePicker.date]; here

的文档