Search code examples
iosnsdateformatter

How do I ignore some characters when getting date from string using NSDateFormater? Also, is there any reference for NSDateFormatter?


My problem is simple. I have strings in the format "16th Sep 2015"

When generating the date string, I used the NSDateFormatter as "d MMM yyyy" and then manually modified it to insert the date suffixes using a switch case.

Now, I need to extract date again.

Is there any way to ignore those 2 letters?

Also, I have been learning NSDateFormatter by using Google and just following posts like this but all my questions are not answered and sometimes, there is a mismatch in behaviour described.

Is there a standard reference by Apple where the Date Formatter codes are described?


Solution

  • NSDateformatter does not support days with ordinal indicators, but you could use a regular expression to strip the indicators

    var dateString = "16th Sep 2015"
    if let range = dateString.range(of: "(st|nd|rd|th)", options: .regularExpression) {
        dateString.removeSubrange(range)
    }    
    let formatter = DateFormatter()
    formatter.locale = Locale(identifier: "en_US_POSIX")
    formatter.dateFormat = "dd MMM yyyy"
    let date = formatter.date(from: dateString)!
    print(date)
    

    Or in Objective-C

    NSMutableString *dateString = [NSMutableString stringWithString:@"16th Sep 2015"];
    
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"(st|nd|rd|th)" options:nil error:nil];
    [regex replaceMatchesInString:dateString options: nil range: NSMakeRange(0, 4) withTemplate:@""];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    formatter.dateFormat = @"d MMM yyyy";
    NSDate *date = [formatter dateFromString:dateString];
    NSLog(@"%@", date);