Kar Wai Kar Wai - 2 months ago 14
iOS Question

NSDate formatting for some date is not the valid date

currently I have a piece of code that is converting a set of string (eg. 900130) keyed in by user to a date using yyMMdd(Malaysia IC) format. My code for converting the string as follows:

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyMMdd"];
date = [dateFormat dateFromString:temp]; // temp = string key in by user


The problem didn't occur to me when I was running some test, but when I gave it to someone else to test it, the problem occur where the string 490130 which should be converted to 30/1/1949 was converting it to 30/1/2049.

How do I convert 490130 to 30/1/1949 instead of 30/1/2049

Answer

NSDateFormatter assumes 20xx for a 2-digit year if the year is less than 50 and 19xx for a 2-digit year if the year is greater than 50. I forget which it assumes when the year is 50.

It seems you want a cutoff different from 50. There is no built-in support for using a different cutoff.

One option is to look at the first two characters and see if it is below or after your cutoff. Then prepend either 19 or 20 to the start of the string as needed. Then parse the string using yyyyMMdd.

Comments