我以编程方式为ios 7创建了一个日期选择器,并设置了最大和最小日期。但是在某些特定的12月日,它会返回错误的年份。
[fromDatePicker addTarget:self action:@selector(fromDatePickerAction:) forControlEvents:UIControlEventValueChanged];
NSDate *date = [NSDate date];
NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier: NSGregorianCalendar];
NSDateComponents * components = [[NSDateComponents alloc] init];
NSDateComponents *monthComponents = [gregorian components:NSMonthCalendarUnit fromDate:date];
int currentMonth = [monthComponents month];
NSDateComponents *dayComponents = [gregorian components:NSDayCalendarUnit fromDate:date];
int dayss=[dayComponents day];
[components setYear:0];
NSDate * minDate = [gregorian dateByAddingComponents: components toDate: date options: 0];
[components setYear:0];
[components setMonth:12-currentMonth];
[components setDay:31-dayss];
NSDate * maxDate = [gregorian dateByAddingComponents: components toDate: date options: 0];
fromDatePicker.minimumDate=minDate;
fromDatePicker.maximumDate=maxDate;
[self.view addSubview:fromDatePicker];
- (void) fromDatePickerAction:(id)sender{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm aa"];
[self.delegate didTouchAddNotePicker:[dateFormatter stringFromDate:[fromDatePicker date]]];
NSLog(@"%@",[dateFormatter stringFromDate:[fromDatePicker date]]);
//_lblDate.text=[dateFormatter stringFromDate:[fromDatePicker date]];
}
在这里,我选择图1所示的日期。但它返回图2中的日期
请帮助解决这个问题
答案 0 :(得分:3)
通过将[dateFormatter setDateFormat:@" YYYY-MM-dd hh:mm aa"]更改为[dateFormatter setDateFormat:@" yyyy-MM-dd hh:mm aa& #34;]在日期选择器选择器方法
中Please click this link to know about the difference between YYYY and yyyy