NSDatePicker with date in yy to yyyy format

798 views Asked by At

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.

1

There are 1 answers

2
DarkDust On

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.