0

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?

ilgaar
  • 804
  • 1
  • 12
  • 31
  • Related: [Is there a way to convert a natural language date NSString to an NSDate](https://stackoverflow.com/questions/5878528/is-there-a-way-to-convert-a-natural-language-date-nsstring-to-an-nsdate) – Willeke Nov 24 '22 at 10:05
  • Have you tried to set the `lenient` property of `NSDateFormatter` to `TRUE`? – mschmidt Nov 24 '22 at 10:06
  • `setLenient:YES` will not help in this case, and the resulting date would still be `null`, It's important to know that If a formatter is set to be lenient, when parsing a string it uses heuristics to guess at the date which is intended. As with any guessing, it may get the result date wrong (that is, a date other than that which was intended). – ilgaar Nov 24 '22 at 16:18
  • Use `NSDataDetector` to convert the string into an `NSDate`. – HangarRash Nov 24 '22 at 16:38

1 Answers1

0

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);
vadian
  • 274,689
  • 30
  • 353
  • 361
  • It actually supports ordinal suffixes but not in English because the suffix is not supposed to be there. – Sulthan Nov 24 '22 at 10:31