0

I have as NSDatePicker, where I enter 0023 and I expect it to change it to 2023. My logic is to convert the yy to yyyy based on +-50 years.

But the default behavior of NSDatePicker changes it to 0023 etc.

What I need to do to show in yyyy format with nearest 50 years range.

Is there any way to do it through Interface Builder or through codes.

Your help will be highly appreciable.

Kaushik
  • 17
  • 3

1 Answers1

0

It does not "change" 0023 to 0023, it leaves it at 0023, which is correct the correct behaviour. You'd need to manually check and fix this yourself. Maybe like (untested):

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar
    components:NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit 
    fromDate:myPossiblyIncorrectDate
];
NSDate *correctedDate;

if ([components year] < 100) {
    NSUInteger currentYearLastDigits = 13; // Insert logic to get current year here.
    NSUInteger yearLastDigits = [components year];

    if (yearLastDigits > currentYearLastDigits) {
       [components setYear:1900 + yearLastDigits];
    } else {
       [components setYear:2000 + yearLastDigits];
    }

    correctedDate = [calendar dateFromComponents:components];
} else {
    correctedDate = myPossiblyIncorrectDate;
}

Depending on how exact you need this to be, you might want to get/set more components. See the NSCalendar constants.

But it would be better to catch the wrong year number before the number is even interpreted as year number since the date might be invalid otherwise.

DarkDust
  • 90,870
  • 19
  • 190
  • 224
  • Thanks for answer, i tried above code with few changes it worked fine. But I needed to use above in an action button, is there any way to execute the above as soon as textDidEndEditing... kind of delegate? – Kaushik Aug 08 '13 at 09:12
  • @Kaushik Don't know how to right now. Please ask a new question regarding that (but search StackOverflow first, I'm sure you can find a similar question to the editing problem). – DarkDust Aug 08 '13 at 09:15