How do I get the alphanumeric abbreviated day of month in objective-c?

60 Views Asked by At

NSDate in Objective-c used to have dateWithNaturalLanguageString which accepted the use of abbreviated alphanumeric days of month with in strings like: @"Aug 2nd, 2010", but this method is deprecated, and I am trying to use NSDateFormatter instead:

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"MMM dd, yyyy"];

but I can not use the following string with the above format:

    NSDate date* = [dateFormatter dateFromString:@"Aug 2nd, 2010"];

since it will cause the date to be null due to incompatible format. I checked out the unicode standard date formats but I could not find anything that has an abbreviated alphanumeric day of month, and I am forced to use @"Aug 02, 2010" instead. But this is not desirable since I need abbreviated alphanumeric day of month both for setting a date from a string and getting a string from a date. After searching hours through various documentations I am out of ideas. Is there anyway other than the deprecated dateWithNaturalLanguageString? Or do I have to make a method of my own?

1

There are 1 best solutions below

1
On

NSDateFormatter does not support ordinal suffixes (in English).

An alternative is to remove the suffix with Regular Expression

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"en_US_POSIX"];
dateFormatter.dateFormat = @"MMM dd, yyyy";
NSString *dateString = @"Aug 2nd, 2010";
NSString *trimmedString = [dateString stringByReplacingOccurrencesOfString:@"(\\d{1,2})(st|nd|rd|th)"
                                                                withString:@"$1"
                                                                   options: NSRegularExpressionSearch
                                                                     range:NSMakeRange(0, dateString.length)];
NSDate *date = [dateFormatter dateFromString:trimmedString];
NSLog(@"%@", date);