选择UIDatePicker中的日期时出现问题(iPhone)

3
我正在使用UIDatePicker表单,但问题在于当我选择日期和时间时,文本字段中的时间比选择器显示的时间晚了5个小时。我已经阅读到date picker存在一个bug,但我不知道如何解决这个问题。我需要显示墨西哥的时间。我尝试过以下代码,但没有任何改变。

datePicker.calendar = [NSCalendar autoupdatingCurrentCalendar];
datePicker.timeZone = [NSTimeZone localTimeZone];
datePicker.locale = [NSLocale currentLocale];

有人能帮我解决这个问题吗?谢谢!


如果时间总是比实际时间晚5个小时,为什么不直接减去这5个小时呢? - msgambel
你使用什么代码来打印日期?根据生成日期字符串的方式,你可能会得到UTC时间格式。 - Ben Mosher
2个回答

3
如果您还没有使用它,我建议采取以下措施:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateStyle:NSDateFormatterMediumStyle];
[df setTimeStyle:NSDateFormatterMediumStyle];

NSString *stringToDisplay = [df stringFromDate:myDateObject];

NSDateFormatter 应该为您处理任何时区问题。您可以在此处阅读更多信息。这里


0

做这个:这会帮助你

//Date Picker
(void)textFieldDidBeginEditing:(UITextField *)aTextField {    
  [aTextField resignFirstResponder];  

  pickerViewPopup = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:nil];  

  UIDatePicker *pickerView = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 44, 0, 0)];  
  pickerView.datePickerMode = UIDatePickerModeDate;  
  pickerView.hidden = NO;  
  pickerView.date = [NSDate date];  

  UIToolbar *pickerToolbar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 44)];  
  pickerToolbar.barStyle = UIBarStyleBlackOpaque;  
  [pickerToolbar sizeToFit];  

  NSMutableArray *barItems = [[NSMutableArray alloc] init];  

  UIBarButtonItem *flexSpace = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];  
  [barItems addObject:flexSpace];  

  UIBarButtonItem *doneBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneButtonPressed:)];  
  [barItems addObject:doneBtn];  

  UIBarButtonItem *cancelBtn = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonPressed:)];  
  [barItems addObject:cancelBtn];  

  [pickerToolbar setItems:barItems animated:YES];  

  [pickerViewPopup addSubview:pickerToolbar];  
  [pickerViewPopup addSubview:pickerView];  
  [pickerViewPopup showInView:self.view];  
  [pickerViewPopup setBounds:CGRectMake(0,0,320, 464)];    
}  

(void)doneButtonPressed:(id)sender{  
//Do something here here with the value selected using [pickerView date] to get that value  
    [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];  
}  

(void)cancelButtonPressed:(id)sender{  
  [pickerViewPopup dismissWithClickedButtonIndex:1 animated:YES];  
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接