我在我的应用程序中使用UIDatePicker,当我使用所选择的日期:
NSDate *date = picker.date;
picker.date
在我选择的日期前一天返回。
知道为什么会这样吗?
UIDatePicker
将显示您当地时区的日期和时间。然而,NSDate
没有任何时区的概念,因为它存储了自参考日期以来的绝对秒数。当NSLogging
设置日期时,它以GMT格式显示日期和时间。我希望如果您计算出您的本地时区与GMT的差异,您将看到它是正确的日期。
尝试创建一个具有适当区域设置的NSDateFormatter或NSCalendar,并通过它传递日期。
有关这个常见主题的进一步阅读,请参阅另一位SO贡献者撰写的网站。
试一试
NSDate* sourceDate = [NSDate date];
NSTimeZone* sourceTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];
NSTimeZone* destinationTimeZone = [NSTimeZone systemTimeZone];
NSInteger sourceGMTOffset = [sourceTimeZone secondsFromGMTForDate:sourceDate];
NSInteger destinationGMTOffset = [destinationTimeZone secondsFromGMTForDate:sourceDate];
NSTimeInterval interval = destinationGMTOffset - sourceGMTOffset;
NSDate* destinationDate = [[[NSDate alloc] initWithTimeInterval:interval sinceDate:sourceDate] autorelease];
//你可以使用任何你喜欢的
NSString *dateOutput = [[[NSString alloc] initWithFormat:@"%@", destinationDate]autorelease];
self.dateLabel.text = dateOutput;
记得创建NSDate,然后输出一个有效的时区和日历!
NSDate只表示绝对时间点。它没有时区(纽约、巴塞罗那……)或日历(公历、希伯来语……)的概念。
UIDatePicker默认返回一个带有系统NSCalendar和NSTimeZone的NSDate,但是当您稍后尝试打印它时,您不格式化输出。这里可能有不匹配。
所以首先你需要正确设置UIDatePicker,然后用NSDateFormatter转换输出,这样它就知道正在使用的日历和时区。
UIDatePicker初始化并打印结果的示例代码:
- (void)viewDidLoad
{
[super viewDidLoad];
// init the UIDatePicker with your values
// by default UIDatePicker inits with today, system calendar and timezone
// Only for teaching purposes I will init with default values
NSDate * now = [[NSDate alloc] init];
[_datePicker setDate: now]
animated: YES];
_datePicker.timeZone = [NSTimeZone localTimeZone];
_datePicker.calendar = [NSCalendar currentCalendar];
[_datePicker addTarget: self
action: @selector(getDatePickerSelection:)
forControlEvents:UIControlEventValueChanged];
}
-(void)getDatePickerSelection:(id) sender
{
// NSDateFormatter automatically inits with system calendar and timezone
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
// Setup an output style
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeStyle:NSDateFormatterShortStyle];
// Medium style date, short style time => "Nov 23, 1937 3:30pm"
NSString *dateString = [dateFormatter stringFromDate:date];
}
检查我对另一个非常相似的问题的回答:
使用NSDateFormatter输出NSDate
您检查时区了吗?
当你打印一个NSDate
时,它将使用GMT作为它的时区。
如果你将系统时区设置为NSDateFormatter,你可能会得到另一个日期,因为它将采用时区并相应地计算时间。
添加以下代码并查看输出是否正确:
NSDate *date = picker.date;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
[dateFormatter setTimeZone:NSDateFormatterNoStyle];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSLog(@"Date: %@", [dateFormmater stringFromDate:date]);
[dateFormatter release], dateFormatter = nil;
只需添加一行代码
self.datePicker.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0];
0表示GMT 00。根据你的时区添加。