UIDatePicker不显示正确的时间

时间:2012-05-17 09:54:06

标签: iphone ios datepicker timepicker

我正在使用datePicker来创建一个timePicker。当我单击textField时,选择器打开,我在其中选择了时间,之后所选时间将显示在该文本字段中。在我的情况下,除文本字段中显示的时间外,一切正常。它显示错误的时间,特别是几分钟。

这是我创建选择器的代码

timePickerView =  [[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, 320, 260)];
timePickerView.backgroundColor = [UIColor clearColor];

    //create toolbar using new
UIToolbar *toolbar1;
toolbar1 = [UIToolbar new];
    //toolbar.barStyle = UIBarStyleBlackTranslucent;
toolbar1.tintColor = [UIColor colorWithRed:0.627 green:0.627 blue:0.655 alpha:1.000];
    //[UIColor colorWithRed:0.6 green:0.6 blue:0.6 alpha:0.6];
[toolbar1 sizeToFit];
toolbar1.frame = CGRectMake(0, 0, 320, 50);

    //Add buttons
UIBarButtonItem *doneButtone1 = [[UIBarButtonItem alloc]
                                initWithBarButtonSystemItem:UIBarButtonSystemItemDone
                                target:self action:@selector(dismissPicker:)];

    //Use this to put space in between your toolbox buttons
UIBarButtonItem *flexItem1 = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace
                                                                          target:nil
                                                                          action:nil];

    //Add buttons to the array
NSArray *items1 = [NSArray arrayWithObjects: flexItem1, doneButtone1, nil];

    //release buttons
[doneButtone1 release];
[flexItem1 release];

    //add array of buttons to toolbar
[toolbar1 setItems:items1 animated:NO];
[timePickerView addSubview:toolbar1];
[toolbar1 release];

    UIDatePicker *timePicker = [[UIDatePicker alloc]initWithFrame:CGRectZero];
timePicker.autoresizingMask=UIViewAutoresizingFlexibleWidth;
timePicker.datePickerMode = UIDatePickerModeTime;
timePicker.frame = CGRectMake(0, 50.0f, 320.0, 216);
timePicker.tag = 222;
[timePicker addTarget:self action:@selector(selectTime:) forControlEvents:UIControlEventValueChanged];
[timePickerView addSubview:timePicker];
[timePicker release];

这是在textfield中显示时间的代码

UIDatePicker *picker =(UIDatePicker *)sender;
DLog(@"%@",picker);

NSDateFormatter *df1 = [[NSDateFormatter alloc] init];
df1.dateStyle = NSDateFormatterMediumStyle;
    //if(picker.tag =222) {
    [df1 setDateFormat:@"HH:MM"];       
    self.timeTF.text = [NSString stringWithFormat:@"%@",[df1 stringFromDate:picker.date]];
    //timeTF.text=[df1 stringFromDate:[NSDate date]];

[df1 release];

正确显示时针,但分钟显示总是5

我的代码中有什么错误。任何人都可以帮助我找到答案。

1 个答案:

答案 0 :(得分:2)

这一行是问题所在:

[df1 setDateFormat:@"HH:MM"];

MM是月份,即May = 5

您应该使用mm