Search code examples
ios7datepicker

iOS: DatePicker selector shows exact value but it returns wrong date


I create a date picker programmatically for ios 7 and set maximum and minimum date.But it return wrong year for some particular december days.

    [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]];

}

Here I choose this date shown in figure But it returns this date

Here I choose this date shown in figure 1.But it returns the date in figure 2

Please help to solve this problem


Solution

  • This problem is solved by changing [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm aa"] to [dateFormatter setDateFormat:@"yyyy-MM-dd hh:mm aa"] in date picker selector method

    Please click this link to know about the difference between YYYY and yyyy