在我正在开发的iPhone应用程序中,我在日期方面遇到了一些问题。我没有广泛使用它们,所以这是非常基本的,但我仍然在做错了。当我通过简单的月/日/年UIDatePicker获取我的NSDate时,我会选择例如2011年12月24日。但是,当我通过NSDateFormatter根据本地时区打印出NSDate时,我会得到一个MM-DD-YY输出,这个输出比我选择的那天少一天。这是我所有相关的日期输入/输出代码:
我通过UIDatePicker使用以下方法接收与自定义对象关联的日期:
- (void)willPresentActionSheet:(UIActionSheet *)actionSheet // Protocol method for UIActionSheetDelegate
{
// Among other things, add our UIDatePicker to a UIActionSheet that we pop up.
NSDate* currentDate = [NSDate date];
[pickerView setDate:currentDate];
[pickerView setMaximumDate:currentDate];
[pickerView setDatePickerMode:UIDatePickerModeDate]; // We don't need time for this.
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{ // UIActionSheetDelegate Protocol method for saving date change if OK is selected, else if cancel is selected, do nothing.
[self.customObjectBeingInput setDate:[ourDatePicker date]]; // Set object date to selected date in date picker.
}
至于将日期输出到我设置的UILabel,这里是正在发生的事情:
NSDateFormatter *dateformatter = [[NSDateFormatter alloc] init]; // Format the date into human-readble format.
[dateformatter setDateFormat:@"MM-dd-yyyy"];
[dateformatter setTimeZone:[NSTimeZone systemTimeZone]];
[dateformatter setDateStyle:NSDateFormatterShortStyle];
NSString *formattedDate = [dateformatter stringFromDate:[self.customObject date]];
[[self.customViewController customObjectDateLabel] setText:formattedDate];
[dateformatter release];
dateformatter = nil;
我应该为UIDatePicker
输入设置与时区相关的内容,或者由于NSDate
返回绝对时间点而不管用户的时区,我们通常可以忽略地点问题,至少在输入阶段?
我绝对认为这与输出阶段有关,而不是我如何通过UIDatePicker
接受日期,但我不知道我做错了什么干得好。