UIDatePicker,在UITextView中用作字符串时为+/- 1天差异

时间:2012-06-20 07:45:33

标签: iphone xcode nsdateformatter uidatepicker nsdatecomponents

我有2个日期选择器,每个选择器都是以太(280天) 拣货员改变正确,但mydatepicker.date当NSlog或UITextfield时,日期变为日期 - 1天或日期+ 1天

这是我的代码:

第一个选择器:

int daysToAdd = -280;  
// set up date components
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:daysToAdd];
// create a calendar
NSCalendar *addingdays = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *newDate = [addingdays dateByAddingComponents:components toDate:dueDatePickerView.date options:0];
lastPerPickerView.date = newDate;
 NSLog(@"%@",newDate);

第二个:

int daysToAdd2 = 280;  
// set up date components
NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
[components setDay:daysToAdd2];
// create a calendar
NSCalendar *addingdays2 = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *newDate2 = [addingdays2 dateByAddingComponents:components toDate:lastPerPickerView.date options:0];
dueDatePickerView.date = newDate2;
NSLog(@"%@",newDate2);

如果第一个选择器的日期是12-12-2012 输出是11-12-2012

在我的代码中,我给了他们正确的

  lastPerPickerView.datePickerMode = UIDatePickerModeDate;

2 个答案:

答案 0 :(得分:1)

您获得的输出在逻辑上是正确的。但是如果你想根据你的要求输出我认为你应该将值280改为279。

答案 1 :(得分:1)

尝试将此行添加到您的代码

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT+0:00"]];

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]];